Justin Paul Silva

Email Masking with Javascript

Posted on

Spam is one of the biggest annoyances on the internet. The problem with all the spam blockers available, usually built into email services like gMail, is that nothing will block 100% of spam without blocking the emails you want to get through. The best way to avoid spam is to stop spammers from finding your email address in the first place, by somehow masking it when you put it online. There are several methods of doing this, including replacing your email address text with an image of it, using just plain text with no email link (usually something like “justin [at] jpsilva [dot] com”), or using a contact form in place of a mail-to link. The best method must fit all the following goals:

The method I use involves using Javascript to turn plain text into a standard HTML email link. Above, I said that the method must not ‘require’ Javascript, and it doesn’t. If the user has Javascript turned off, they will be left with the plain text version of the email address, which they are still able to read. Javascript just makes it a little easier for them. I based this method on an article about email masking that said that spiders cannot execute Javascript. That was quite a while ago, so I’m not sure how true it is now, but I’ve been using this method for a couple years and I still don’t receive spam for this email address. The method is very simple:

HTML Code

<a class="email">nobody at example dot com</a>

Original output (What the user sees)

nobody at example dot com

That’s it for the HTML. It’s a link that doesn’t do anything, but the email address is there, easy to be read, even by screen readers (unlike the image replace method). To turn this into a functional link, we just need a little bit of Javascript. If you already use jQuery on your site, just add the following bit of code to your Javascript file:

Javascript (for jQuery)

$(function(){ $(".email").each(function (){ $(this).html($(this).html().replace(/ at /, "@").replace(/ dot /, ".")); $(this).attr('href', "mailto:" + $(this).html()); }); };

You can download jQuery free here.

If you have no need for jQuery and just want something small and eay, I recommend using Sizzle, the not-so-powerful CSS selector engine used in jQuery.

Javascript (for Sizzle)

window.onload = function(){ emails=Sizzle(".email"); if(emails){ for(i=0;i<emails.length;i++){ emails[i].href="mailto:"+(emails[i].innerHTML=(emails[i].innerHTML.replace(/ at /,"@")).replace(/ dot /,".")); } } };

You can download Sizzle free here.

HTML after Javascript is executed

<a class="email" href="nobody@example.com">nobody@example.com</a>

Output after Javascript (What the user sees)