Fix Anchor URLs Using MooTools 1.2

By  on  

The administrative control panel I build for my customers features FCKEditor, a powerful WYSIWYG editor that allows the customer to add links, bold text, create ordered lists, and so on. I provide training and documentation to the customers but many times they simply forget to include the "http://" when add links into their content. Essentially, they end up with links that look like:

	<a href="www.davidwalsh.name">Click here</a>

Obviously, that's a problem. Luckily MooTools 1.2 provides a quick fix for that problem for website users.

The MooTools 1.2 Code

window.addEvent('domready', function() {
	$('fix-links').addEvent('click', function() {
		$$('a[href^=www.]').each(function(el) {
			el.set('href','http://www.' + el.get('href').split('www.')[1]);
		});
		alert('Links fixed.');
	});
});

The above solutions is NOT the best solution because it doesn't correct what the search engines see. Have a PHP solution? Submit it! The best solution is to fix the link within the FCKEditor plugin at the time the user adds the link. The code above, however, will buy you a little time to go in and fix any existing errant links.

Recent Features

  • By
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • 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

Discussion

  1. Steinmann

    We are using FCKEditor, and it adds the http part automatically.

    We do have a php domparser that goes thru the whole thing fixing other things tho. Like adding lytebox links to some images etc…

  2. Does Mootools implement the CSS not() selector? If so, then you can use $$('a:not([^=http]').each...

    Good tip!

  3. Jordan

    @Eric Wendelin: That wouldn’t be ideal in a case where the link is meant to be relative.

  4. Caleb

    If there’s a way, it’d be great to have the Javascript check for url errors, and if it finds any, it’ll post the info to a php script, changing the url(s) permanently. I’ve been trying to create a script like that.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!