Accessibly Cloak Email Addresses with jQuery

It’s very common on websites today to find some method of “cloaking” your email address to protect it from spam bots and email scrapers. Some use images (a la Facebook, some (like my friend Rob) encrypt their email address to protect from spam bots, and yet others spell out the syntax.

While talking with my friend Rob, we wanted to write a quick unobtrusive jQuery snippet to grab all email address on a page with their syntax spelled out, and convert them back to proper email syntax (and even turn them into mailto: links.

So, we did:

$(".email").each(function(){
	var ats, dots, address, i;
	ats = [' (at) '];
	dots = [' (dot) '];
	address = $(this).html();
	for ( i = 0; i < ats.length; i++ ) {
		address = address.replace(ats[i], '@');
	}
	for ( i = 0; i < dots.length; i++ ) {
		address = address.replace(dots[i], '.');
	}
	$(this).html('&lt;a href="mailto:' + address + '"&gt;' + address + '&lt;/a&gt;');
});

Check out a very basic example.

Make sure you’re wrapping the obscured email address in a <span/> element with a class name of email – then drop this snippet inside your $(document).ready() function. ¡Viola!

Some additional notes/caveats:

  • You’ll notice that ats and dots are JSON arrays. This allows you to add multiple versions of syntax spelling (i.e. ” at “, ” [at] “, ” at “, etc.)
  • The email class can be assigned to any element in your HTML/XHTML document.
  • The entire innerHTML of the nodes with the email class assigned will be replaced, so choose wisely. <span/>‘s come in handy here.

3 Comments

  1. Jeffrey Herr says…

    Thanks for the nudge. It was easy enough, but I guess I just wanted someone to do it for me! I used this approach on a SquareSpace website. Works great, and is flexible enough for me to choose my own obfuscation patterns to further thwart spammers… Appreciate it!

  2. andy says…

    That’s great! I’m glad it was helpful, thanks for sharing, too!

  3. Beny says…

    Useful. Thanx!

RSS feed for comments on this post. TrackBack URL

Leave a Comment

February 16, 2009

Filed in Uncategorized

There are 3 comments »


« Back to the Blog