Skip to content

Instantly share code, notes, and snippets.

@tedw
Last active December 28, 2015 21:59
Show Gist options
  • Save tedw/7567902 to your computer and use it in GitHub Desktop.
Save tedw/7567902 to your computer and use it in GitHub Desktop.
Mailto Link Generator
// Generate mailto links
// Exmaples: <span data-email="hello[at]threespot.com">Contact Us</span>
// <span data-email="hello[at]threespot.com">hello [at] threespot.com</span>
createMailtoLink: function( $els ) {
// Loop through all mailto placholder elements
for ( var i=0, len=$els.length; i<len; i++ ) {
var $this = $els[i];
var linkText = $this.innerHTML; // Save the link text
var mailto = $this.getAttribute('data-email'); // Get the mailto address
mailto = 'mailto:' + mailto.replace('[at]', '@'); // Convert to actual email address
// Create mailto link
var $link = document.createElement('a');
// Apply any attributes from original element to new link
var origAttr = $this.attributes;
for ( var a=0, b=origAttr.length; a<b; a++ ) {
$link.setAttribute( origAttr[a].nodeName, origAttr[a].nodeValue );
}
// Update href and innerHTML of link
$link.href = mailto;
$link.innerHTML = linkText;
// Insert link and remove placeholder element
var $parentNode = $this.parentNode;
$parentNode.insertBefore( $link, $this );
$parentNode.removeChild( $this );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment