Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Hide email address from spammers with Javascript (See related posts)

function mangle() {
	if (!document.getElementsByTagName && !document.createElement &&
		!document.createTextNode) return;
	var nodes = document.getElementsByTagName("span");
	for(var i=nodes.length-1;i>=0;i--) {
		if (nodes[i].className=="change") {
			var at = / at /;
			var dot = / dot /g;
			var node = document.createElement("a");
			var address = nodes[i].firstChild.nodeValue;

			address = address.replace(at, "@");
			address = address.replace(dot, ".");

			address = address.replace(at, "@");
			address = address.replace(dot, ".");
			node.setAttribute("href", "mailto:"+address);
			node.appendChild(document.createTextNode(address));
			
			var prnt = nodes[i].parentNode;
			for(var j=0;j<prnt.childNodes.length;j++)
				if (prnt.childNodes[j] == nodes[i]) {
					if (!prnt.replaceChild) return;
					prnt.replaceChild(node, prnt.childNodes[j]);
					break;
				}
		}
	}
}


You can use this script, if you'd like to post your email address to your homepage, but don't want to see it picked up by spammers.

Just run it in your onload event handler and mark emails in your HTML as:

<span class="change">markos at gaivo dot net</span>

This way they are still recognizable by those who don't use javascript.

If you need help or want to discuss this code, please do it on my blog.

You need to create an account or log in to post comments to this site.


Click here to browse all 5147 code snippets

Related Posts