Last active
December 28, 2015 21:59
-
-
Save tedw/7567902 to your computer and use it in GitHub Desktop.
Mailto Link Generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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