jQuery Safer Mailto Links  Plugin

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

Recently I realized that jQuery plugins are the way to go for building re-usable, modular code snippets. As a result I have revisited the jQuery Safe Mailto’s function, building a jQuery Plugin to replace it.

Working Example

info[at]kevinleary[dot]net

All instances of “[at]” will be replaces with “@”;
Likewise, [dot] will be replaced with “.”

Plugin Code

jQuery.fn.safeMailTo = function() {
  return this.each(function(){

    var mailtoHref = $(this).attr('href');
    mailtoHref = mailtoHref.replace(mailtoHref,"mailto:" + mailtoHref);
    mailtoHref = mailtoHref.replace("[at]","@");
    mailtoHref = mailtoHref.replace("[dot]",".");

    var mailtoText = $(this).text();
    mailtoText = mailtoText.replace("[at]","@");
    mailtoText = mailtoText.replace("[dot]",".");
    $(this).text(mailtoText);

    var mailtoTitle = mailtoHref.replace("mailto:","Email: ");
    $(this).attr('title',mailtoTitle);

    $(this).click(function(){
      window.location.href = mailtoHref;
      return false;
    });
  });
};

Usage

  1. Include the latest version of jQuery into the HEAD section of the document.
  2. Include jquery.mailto.js into the HEAD section of the document.
  3. Add the .safeMailTo() method onto the selector you wish to modify

Example Implementation

$(document).ready(function(){
  $("a[rel='email']").safeMailTo();
});

Download

Resources

Meet the Author

Kevin Leary, WordPress Consultant

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