In the 1990s, there was a fashion to put Javascript code directly into <a>
href attributes, like this:
<a href="javascript:alert('Hello world!')">Press me!</a>
And then suddenly I stopped to see it. They were all replaced by things like:
<a href="#" onclick="alert('Hello world!')">Press me!</a>
For a link whose sole purpose is to trigger Javascript code, and has no real href
target, why is it encouraged to use the onclick
property instead of the href
property?
The execution context is different, to see this, try these links instead:
<a href="javascript:alert(this.tagName)">Press me!</a> <!-- result: undefined -->
<a href="#" onclick="alert(this.tagName)">Press me!</a> <!-- result: A -->
javascript:
is executed in the global context, not as a method of the element, which is usually want you want. In most cases you're doing something with or in relation to the element you acted on, better to execute it in that context.
Also, it's just much cleaner, though I wouldn't use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:
$('a').click(function() { alert(this.tagName); });