DEV Community

Cover image for jQuery Mailto Links Plugin
Kevinleary.net
Kevinleary.net

Posted on Originally published at kevinleary.net

jQuery Mailto Links Plugin

You may want to check out the reCAPTCHA Mail Hide service, it provides better protection than the method described here.

The jQuery Mailto Plugin will safely protect your mailto: anchors links with jQuery. Features include:

  • REGEX replacement
  • Updated status message
  • Simplified usage using a class rather than the rel attribute to target mailto: links
  • Leaner code

See a demo

Markup

<a href="info(at)kevinleary.net" class="email">info(at)kevinleary.net</a>
Enter fullscreen mode Exit fullscreen mode

jQuery Plugin

jQuery.fn.mailto = function() {
    return this.each(function(){
        var email = $(this).html().replace(/\s*\(.+\)\s*/, "@");
        $(this).before('[' + email + '](mailto: "Email ")').remove();
    });
};
Enter fullscreen mode Exit fullscreen mode

Initialize

$('.email').mailto();
Enter fullscreen mode Exit fullscreen mode

Above is the easiest way to setup this plugin. Of course, I prefer to add a little more logic to make things more intuitive.

Advanced Usage

if ( $('a.email').length > 0 ) {
    $.getScript('/path/to/jquery.mailto.js',function(){
        $('a.email').mailto();
    });
}
Enter fullscreen mode Exit fullscreen mode

What this does is first check to see if there are any anchor links in the document that have a class of “email”. If there are, we’ll load in the jquery.mailto.js file, and run a function once it has been loaded. This function (or callback) runs the mailto() method on all email anchors.

Why use REGEX in this version?

I’ve used REGEX in place of replace() for this version because it renders the browser message to display emails correctly. With my previous versions some users could see “you[at]domain[dot]com” in the bottom left message of their browsers. REGEX takes care of this little mishap and displays the rendered email address.

See a demo

Download

Top comments (0)