[javascript] Better way to call javascript function in a tag

Which of the following ways is a better way to call a js function from an a tag?

<a href="javascript:someFunction()">LINK</a>

OR

<a href="#" onclick="someFunction();" return false;">LINK</a>

I have seen this question here, but it says <span onclick="someFunction()"> is a better option. But due to some reasons I have to use <a> links.

EDIT: I am looking for a cross browser & cross platform solution which should work on androids & iPads too.

This question is related to javascript html

The answer is


Some advantages to the second option:

  1. You can use this inside onclick to reference the anchor itself (doing the same in option 1 will give you window instead).

  2. You can set the href to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();" and return false from inside the function or onclick="return someFunction(); return false;" to prevent default action).

  3. I've seen weird stuff happen when using href="javascript:someFunction()" and the function returns a value; the whole page would get replaced by just that value.

Pitfalls

Inline code:

  1. Runs in document scope as opposed to code defined inside <script> tags which runs in window scope; therefore, symbols may be resolved based on an element's name or id attribute, causing the unintended effect of attempting to treat an element as a function.

  2. Is harder to reuse; delicate copy-paste is required to move it from one project to another.

  3. Adds weight to your pages, whereas external code files can be cached by the browser.


I’m tempted to say that both are bad practices.

The use of onclick or javascript: should be dismissed in favor of listening to events from outside scripts, allowing for a better separation between markup and logic and thus leading to less repeated code.

Note also that external scripts get cached by the browser.

Have a look at this answer.

Some good ways of implementing cross-browser event listeners here.


Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.

Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.

The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.