Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

Email Protection with MooTools JavaScript v2

8 Responses »

Earlier this week I posted an article describing how you can protect your email links from spambots using MooTools. After some suggestions, I've made some improvements to my system.

The XHTML

	
	<span rel="david|davidwalsh.name" class="email custom-class">Email me!</span>
	

I've switched to using a span tag instead of an anchor to prevent search engines from seeing dead links. We put the modified email address in the rel attribute.

The MooTools JavaScript


window.addEvent('domready', function() {
	$$('.email').each(function(el) {
		var anchor = new Element('a', {
			href: 'mailto:' + el.get('rel').replace('|','@'),
			'class': el.get('class'),
			'text': el.get('text')
		}).replaces(el);
	});
});

I create an anchor element and replace the span element that was originally there.

Thank you to everyone that shared their ideas -- we came up with a better script!

Discussion

  1. September 12, 2008 @ 4:05 pm

    This version is way cleaner, I assume I can change the pipe to any weirdo special character like &#98237980127r5981327r0981; then do the replace?

  2. neutral
    September 14, 2008 @ 7:48 pm

    Have you tested how effective is it against spam yet?

    If it picks up any spam at all, I guess the next step would be to add in ROT13 to your approach.

  3. October 12, 2008 @ 7:10 am

    Internet explorer 7 doesn’t like the “,” after ‘class’: el.get(‘class’)
    That throws an error…

  4. birke
    March 17, 2009 @ 12:22 am

    I tried to use this but my Browser does nothing if I click on the E-Mail me text.

  5. March 17, 2009 @ 9:00 am

    @Birke: Works for me.

  6. wes
    March 19, 2009 @ 7:15 am

    I had to add ‘text’: el.get(‘text’) to the new anchor element to be able to show the “Email Me” text.

  7. March 19, 2009 @ 7:49 am

    @Wes: Good catch — updated that and compatibility with MooTools 1.3 (removed $each).

  8. March 8, 2010 @ 2:57 pm

    Thanks! The only thing i did different was to use title instead of rel. rel isn’t valid in a span.

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!