Assign Anchor IDs Using MooTools 1.2

By  on  

One of my favorite uses of the MooTools JavaScript library is the SmoothScroll plugin. I use it on my website, my employer's website, and on many customer websites. The best part about the plugin is that it's so easy to implement.

I recently ran into a situation where the customer wanted the feature on a super-tight budget. We set them up with PHP includes which was a great help in allowing me to add the smoothscroll.js JavaScript file to every page, but in order to use SmoothScroll, every anchor needs an ID. Of course, their previous developer (we only moved their old content into a new system -- didn't update the HTML code) didn't add an ID attribute to each anchor because there wasn't a reason to. Unfortunately, their thousands of pages were loaded with anchors so we didn't have time to add id attributes to them.

Using some MooTools 1.2 magic, I figured out a way to make this work in no-time.

window.addEvent('domready',function() { 
	//makes sure anchors have ids
	$$('.content a').each(function(el) {
		if(el.get('name') && !el.get('id'))
		{
			el.set('id',el.get('name'));
		}
	});
	
	//smooooooth scrolling enabled
	new SmoothScroll({ duration:700 }, window); 
});

Before enabling SmoothScroll, I look for all anchors and add an ID attribute that mirrors the anchor's name. Quick fix to a potentially big problem.

Note: If you're good with regular expressions, please share a PHP-compliant regular expression that would find all anchors and add an ID attribute that mirrors the anchor's name. You will achieve immortality on my site!

Recent Features

  • By
    Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event...

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

Incredible Demos

  • By
    Flexbox Equal Height Columns

    Flexbox was supposed to be the pot of gold at the long, long rainbow of insufficient CSS layout techniques.  And the only disappointment I've experienced with flexbox is that browser vendors took so long to implement it.  I can't also claim to have pushed flexbox's limits, but...

  • By
    Introducing MooTools LinkAlert

    One of my favorite Firefox plugins is called LinkAlert. LinkAlert shows the user an icon when they hover over a special link, like a link to a Microsoft Word DOC or a PDF file. I love that warning because I hate the surprise...