Cool JavaScript Snippet
November 8th, 2007
I was thrilled to see Design Melt Down’s post yesterday about brown websites (can you guess whether or not I like those?), and I came across HappilyCreate.com. I recognized the site from an earlier visit, but I’m not sure how I had happened upon it (StumbleUpon is my guess.) So I was perusing, checking stuff out, really enjoying the whole feel of the site. Then I decide to click the “email” link. I was half expecting to go to a contact page (this is what I was looking for when I clicked it, I like to see how people design these pages), but there was a slight pause. Then the typical launching of a new email in my email client. “Huh? What just happened?” I thought.
Clearly this wasn’t a typical <a href=”mailto:email@email.com”> link. What was that slight pause? I deduced there was some JavaScript magic happening. I think you know what came next (well, after closing the email that launched); right click - view source. Sure enough, there was a piece of JavaScript making things work. Now, I know “they” say you shouldn’t use JavaScript in a link tags, but don’t we want to prevent a ton of incoming spam? Aren’t we entitled to protect our email addresses? This is a totally acceptable use of JavaScript, no matter what “they” say.
I wanted to share what I found to be a clean way to send an email without exposing an email address to the dreaded spambots. I contacted Robert (the site designer) and he said it would be fine to share his “secret”, so here’s the JavaScript:
function emailMe(user,domain){
emailaddress = “mailto:” + user + “@” + domain;
window.location = emailaddress;}
And the HTML:
<a href=”#” onclick=”javascript:emailMe(’address’,'domain.com’)” id=”email” target=”_self”>email</a>
Isn’t that short, sweet, and effective? I had used a different technique before, but it involved passing in the email string in reverse, and then reversing the passed in argument, and sending that the mailto:, blah, blah, blah. It was at least twice as many lines of ugly code. This way is much better, I hope you can put it to use!



