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
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
- Include the latest version of jQuery into the HEAD section of the document.
- Include jquery.mailto.js into the HEAD section of the document.
- Add the .safeMailTo() method onto the selector you wish to modify
Example Implementation
$(document).ready(function(){
$("a[rel='email']").safeMailTo();
});
Download
- jQuery Safe Mailto Plugin JavaScript (.js)
- jQuery Safe Mailto Plugin ZIP (archived)