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

Kevin Leary

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:

  • “[email]” will be replaced with “mailto”
  • “[at]” will be replaced with “@”
  • “[dot]” will be replaced with “.”
  • The anchor’s title tag will be automatically generated to display the correct email address. This will allow users to see the email address. Many users often wish to send email directly from their web-based email, so a mailto: is of little use to them.

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.

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.