Kevin Leary is a Web User Interface Designer and Front End Developer specializing in standards compliant XHTML, CSS and JavaScript.

Ramblings and articles about Web Design, JavaScript, jQuery, CSS, XHTML and life.

Safe MailTo’s with jQuery

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

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

JavaScript / jQuery

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(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:

1
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.

Comments

One Response to “Safe MailTo’s with jQuery”

  1. Oscar Godson on July 8th, 2008 at 2:58 pm

    In case someone else is using this I also added some of my own code to it. I added a simple:

    $(this).append(mailtoVisible);

    and this way I can take out the string between the tags and make it even harder for the spiders. I also changed your click function to do this:

    window.location.href = mailtoVal; so that the mailto still works.

Say something