Safe email mailto links using jQuery

Here is a quick and easy way to use jQuery for hiding email links from spam bots.

$(document).ready(function() {

 //safe mailto's
 $('a[href*="[at]"][href*="[dot]"]').each(function() {
  var email = $(this).attr('href').split('[at]').join('@').split('[dot]').join('.');
  $(this).attr('href', 'mailto:' + email.toLowerCase());
  if ($(this).text().length == 0) $(this).text(email);
 });
});

First things first… loop through all the anchor tags (aka: links) that have [at] and [dot] in the href attribute. Next replace those placeholders with the proper characters. Then we prepend mailto: and lastly update the inner text of the anchor tag with the email address.

To make this work, your email links would be written as follows…

<a href="info[at]YourDomain[dot]com"></a>

Which would automatically be converted to…

<a href="mailto:info@yourdomain.com">info@YourDomain.com</a>

If you want to include your own text, just use…

<a href="info[at]YourDomain[dot]com">Email Me</a>

Which becomes…

<a href="mailto:info@yourdomain.com">Email Me</a>

Feel free to comment or suggest improvements.

Leave a Reply

Your email address will not be published. Required fields are marked *