This is a simple, well-factored jQuery plug-in. It is written in CoffeeScript. (Not using CoffeeScript? Just paste it in to http://coffeescript.org.)
https://github.com/alanhogan/email-address-de-obfuscator
For understandable reasons, you:
- Do not want to expose raw email addresses in your web pages
- Do not want to serve up HTML that is absolute garbage if JavaScript is off
- Want to let users simply click email addresses to use them (in the common case with JavaScript enabled)
- Don’t want to over-engineer this
Simplest usage?
-
Whenever you have an email address, write it exactly like this, except changing
username
,example
andtld
as appropriate:<a class="js-e">username [AT] example [DOT] tld</a>
-
Include jQuery and this plugin
-
After DOM load, call
jQuery(document).deObfuscateEmailAddresses();
.
Want to get fancy? Read on to customize:
- Where in the DOM changes are made,
- What string substitutions are made, and
- What class name to use when locating obfuscated email addresses.
-
This plugin should work with Zepto (out of the box!) or other jQuery-compatible libraries.
-
Can work with AJAX-loaded content.
If you AJAX content into <div id="my-dynamic-content"></div>
, then immediately call
jQuery('#my-dynamic-content').deObfuscateEmailAddresses();
.
Or just make the global call (jQuery(document)
) again if you don’t feel like scoping it. That should be fine. It’ll just search the whole document again.
- Someone else did the work for you already.
-
Don’t like the class name
js-e
? Choose your own:jQuery(document).deObfuscateEmailAddresses({ "class": "magic-email-link" });
-
[AT]
is too obvious? Cool. Define your own replacements as pairs of a regex or string to search for and a string replacement to make. Pass this as a configuration option:var myReplacements = [ [/\s*at domain\s*/, '@'], ['daht cohm!', '.com'] ]; jQuery(document).deObfuscateEmailAddresses({ replacements: myReplacements });
Usually, you want to show the email address as well as making a mailto:
link. After all, not everyone has an email client set up.
But when that isn’t the case, you can still obfuscate your address by using a data attribute:
<a class="js-e"
data-js-e-addr="foo [at] example [dot] com"
>Contact us</a>
This plugin processes this link into the equivalent of:
<a class="js-e" href="mailto:foo@example.com">Contact us</a>
The data attribute is customizable using the dataKey
configuration option.
Your configuration value does not start with data-
! In the above example,
dataKey
is set to js-e-addr
, not to data-js-e-addr
. Actually, that’s the
default, but you could set it manually.
Absolutely. Here’s a jsFiddle for you.