Forum Moderators: open

Message Too Old, No Replies

protecting email ads with Javascript

         

mr_nabo

8:48 pm on Jan 6, 2008 (gmt 0)

10+ Year Member



Hi,

Complete newbie to Javascript here, so apologies for nthe basicness of the question. I'm trying to protect email addresses in my pages from spambots and can't figure out why the following code results in my mailto: and link text displaying 'undefined' when I've put in the email address I want displayed.

Any ideas?

Thanks

<script>
function email(a,b)
{
document.write(a);
document.write("@");
document.write(b);
}
</script>

<script>
document.write('<a class="email" href="mailto:');
document.write(email("name","domain.com + '">');
document.write(email("name","domain.com") + '</a>');
</script>

penders

12:16 pm on Jan 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



document.write(email("name","domain.com + '">');
document.write(email("name","domain.com") + '</a>');

You seem to have mixed up your quotes and closing brackets a tad...

Should read:

document.write(email('name','domain.com') + '">'); 
document.write(email('name','domain.com') + '</a>');

NB: I tend to keep single quotes (') for JavaScript string delimiters and double quotes (") for HTML attributes - helps to avoid confusion later - but is down to user preference and sometimes necessary to break this rule.

Also, your email() function should return a string (at least where you call the function it is expecting a string to be returned) but you are outputting directly to the page. So I would rewrite your email() function like so:

function email(a,b) { 
return a + '@' + b;
}

mr_nabo

12:34 pm on Jan 7, 2008 (gmt 0)

10+ Year Member



penders:

Thank you very much for this, I'll stick to your advice about keeping HTML attributes within double-quotes, it totally makes sense.

Cheers