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
    9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • By
    Geolocation API

    One interesting aspect of web development is geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user's location. Let's examine how you can...

  • By
    Table Cell and Position Absolute

    If you follow me on Twitter, you saw me rage about trying to make position: absolute work within a TD element or display: table-cell element.  Chrome?  Check.  Internet Explorer?  Check.  Firefox?  Ugh, FML.  I tinkered in the console...and cussed.  I did some researched...and I...