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
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos