iamcal.com

[home] [PDF Version]

Blog Hacks : Javascript email addresses

Originally published 20th June 2003

If you'd like your readers to be able to contact you, then the simplest method is to provide a mailto: link. This, unfortunately, can leave you open to spammers who trawl the web, hunting for addresses. You can get round this using a quick bit of javascript. Instead of the usual:

	<a href="mailto:user@domain.com">

You can use javascript to visually split the address on the page, fooling the spammers:

	<a href="Javascript:window.location.href='mailto:user@'+'domain.com';">

The only downside here is that you break mail links for people who don't have javascript. But don't worry, you can cater for them too:

	<a href="mailto:user AT domain.com"
		onclick="window.location.href='mailto:user@'+'domain.com'; return false;">

Users with javascript will get the proper email address, and users without will get a purposely broken one, which they can fix themselves.

To make it completely compliant, you can also deal with users who aren't using a mouse but do have javascript capable browsers by hooking the onkeypress event and treating it as a click:

	<a href="mailto:user AT domain.com"
		onclick="window.location.href='mailto:user@'+'domain.com'; return false;"
		onkeypress="return this.onclick();">