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
    Send Text Messages with PHP

    Kids these days, I tell ya.  All they care about is the technology.  The video games.  The bottled water.  Oh, and the texting, always the texting.  Back in my day, all we had was...OK, I had all of these things too.  But I still don't get...

  • By
    How to Create a RetroPie on Raspberry Pi – Graphical Guide

    Today we get to play amazing games on our super powered game consoles, PCs, VR headsets, and even mobile devices.  While I enjoy playing new games these days, I do long for the retro gaming systems I had when I was a kid: the original Nintendo...

Incredible Demos

  • By
    Create a Photo Stack Effect with Pure CSS Animations or MooTools

    My favorite technological piece of Google Plus is its image upload and display handling.  You can drag the images from your OS right into a browser's DIV element, the images upload right before your eyes, and the albums page displays a sexy photo deck animation...

  • By
    MooTools, Mario, and Portal

    I'm a big fan of video games. I don't get much time to play them but I'll put down the MacBook Pro long enough to get a few games in. One of my favorites is Portal. For those who don't know, what's...