Reputation: 7971
I have function which needs to be run on click event. However it is working fine with onclick attribute of anchor tag but not working with HREF attribute. It is giving id undefined. Here is demo code
HTML
<a href="javascript:test(this)" id="first">click</a>
JS
function test(obj){
alert(obj.id)
}
Upvotes: 5
Views: 24230
Reputation: 146191
This question already got answers but if you want to use a function as you used in your question then you should use it like
HTML:
<a href="http://heera.it" onclick="return test(this.id)" id="first">click</a>
JS:
function test(obj){
alert(obj);
return false; // this is required to stop navigation to that link
}
notice, return false
, if you have value in href
like this example, then you should use return false
but there are other options like event.preventDefault()
or event.returnValue = false (for IE)
for this reason.
DEMO. Another DEMO (without return false
). Read about this keyword on MDN.
Upvotes: 2
Reputation: 4029
I enjoyed Matt Kruse's Javascript Best Practices article. In it, he states that using the href
section to execute JavaScript
code is a bad idea.
here are some good practices to call javascript on anchor:
<a href="javascript:;" onClick="return DoSomething();">link</a>
<a href="javascript:void(0);" onClick="return DoSomething();">link</a>
<a href="#" onClick="return DoSomething();">link</a>
Upvotes: 0
Reputation: 3662
Use onclick event of the anchor tag. this inside href represents current window.
Upvotes: 0
Reputation: 18387
Here's a fix:
<a href="#" onclick="javascript:test(this);" id="first">click</a>
Upvotes: 3