Safe MailTo’s With  jQuery

There is a newer version of this post available called jQuery Mailto Links Plugin: Version 1.1

Here’s a small snippet I created on the job, I thought some people may find it useful. It was built using jQuery version 1.2.3. The purpose of this snippet is reject those nasty spam bots from stealing your (or your clients) email address from mailto: links.

XHTML

<a dummy-href="[email]info[at]kevinleary[dot]net" rel="email">Kevin Leary</a>

JavaScript / jQuery

$(document).ready(function(){
    $("a[rel='email']").each(function(){
        // Modify the mailto: value
        var mailtoVal = $(this).attr('href');
        mailtoVal = mailtoVal.replace("[email]","mailto:");
        mailtoVal = mailtoVal.replace("[at]","@");
        mailtoVal = mailtoVal.replace("[dot]",".");
        // Auto-generate title tags for users
        var mailtoTitle = mailtoVal.replace("mailto:","Email: ");
        $(this).attr('title',mailtoTitle);
        // onClick Event
        $(this).click(function(){
            window.location.href = mailtoHref;
            return false;
        });
    });
});

Usage

Add rel="email" to each anchor that links to an email address. Next format all of your mailto: links like this:

href="[email]kevin[at]bluehousegroup[dot]com"

Once you have done this you need to link to your copy of jQuery before you link to your JavaScript file.

How it works

The script will basically find all anchor tags with a rel="email" attribute. It will then perform the following actions to each:

That’s it, it’s pretty straight forward.

Other thoughts

One topic I am concerned with is usability. This script will display [email], [at], etc. in the status bar text, making it hard for users to understand what the email address actually is.