Mask email addresses from web-bots via jQuery

This little snippet won't display the email address unless javascript is enabled in the browser, which web-bots do not run. The fully formatted email address won't be present in the html file, just in the browser ram.
HTML • JQuery

Here's your markup for the anchor links. Href can be blank or not included at all. List the username and domain details for the email address in each respective attribute (data-user and data-domain).

<a class="maskedEmail" data-user="john" data-domain="domain.com" href=""></a>
<a class="maskedEmail" data-user="jane" data-domain="domain.com" href=""></a>
<a class="maskedEmail" data-user="bob" data-domain="domain.com" href=""></a>

First we want to make sure the DOM has loaded 100% before proceeding. Then for each anchor with a class of "maskedEmail", the code will extract the values to assemble and populate the href value and text displayed.

$(document).ready(function(){
  $('a.maskedEmail').each(function(){
      var eUsr = $(this).attr('data-user');
      var eDomain = $(this).attr('data-domain');
      var eAddress = eUsr + "@" + eDomain;
      $(this).attr('href','mailto:' + eAddress);
      $(this).html( eAddress );
  });
});

Alternate version with additional subject

<a class="maskedEmail" data-user="john" data-domain="domain.com" data-subject="sample text for subject"></a>
<a class="maskedEmail" data-user="jane" data-domain="domain.com" data-subject="sample text for subject"></a>
<a class="maskedEmail" data-user="bob" data-domain="domain.com" data-subject="sample text for subject"></a>

$(document).ready(function(){
  $('a.maskedEmail').each(function(){
      var eUsr = $(this).attr('data-user');
      var eDomain = $(this).attr('data-domain');
      var eSubject = $(this).attr('data-subject');
      var eAddress = eUsr + "@" + eDomain;
      if (eSubject==null || eSubject=='') {
        $(this).attr('href','mailto:' + eAddress);
      } else {      
        $(this).attr('href','mailto:' + eAddress + '?subject=' + eSubject);
      };
      $(this).html( eAddress );
  });
});

Written by fbrefere001

Posted by fbrefere001 on Friday June 30, 2017