What is the best way and why?
Href?
<a href="javascript:helloworld()">link</a>
onclick?
<a href="#" onClick="helloworld()">link</a>
bind by framework (e.g. jquery)?
<a id="foo" href="#">link</a>
…
$('#foo').live('click',helloworld);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It depends. Usually, you should never have a link that does nothing. What if your users have JavaScript disabled, or it fails to load? You must degrade gracefully to have an accessible website. So, for example, if you have a box that loads with Ajax, you should have it link to an alternative page, then bind the handler in unobtrusive, separate JavaScript:
and in another file:
If the links were generated with JavaScript, then it’s okay to use
#as anhrefmost of the time. However, in that case, you should still be attaching the handlers with JavaScript as opposed to settingonclickininnerHTML(*shudder*).So, generally: if you have an
onclickattribute orjavascript:link in production code, right in your HTML, you’re not separating content, behaviour and presentation; you’re not being accessible; and you’re not being semantic. Don’t do it!