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

Incredible Demos

  • By
    background-size Matters

    It's something that makes all men live in fear, and are often uncertain of. It's never spoken, but the curiosity is always there. Nine out of ten women agree in the affirmative. Advertisers do their best to make us feel inadequate but...

  • By
    &#8220;Top&#8221; Watermark Using MooTools

    Whenever you have a long page worth of content, you generally want to add a "top" anchor link at the bottom of the page so that your user doesn't have to scroll forever to get to the top. The only problem with this method is...

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!