5

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)
}
1
  • 3
    this in that context is the window, not the control. It's not the same an event handler. Here's a fiddle. Commented Sep 20, 2013 at 18:53

5 Answers 5

3

this in that context is the window, not the control. Placing javascript in the href is not the same as an event handler like onclick. Here's a fiddle.

Sign up to request clarification or add additional context in comments.

Comments

3

Here's a fix:

<a href="#" onclick="javascript:test(this);" id="first">click</a>

3 Comments

javascript: is not necessary in an inline event handler.
@Thiago: I know the fix I already mention that in my question. But my question is WHY it is not working.
@amit sorry. I read fast so I just rewrote your function "test" so that it could access id property of your anchor...but I believe that canon already answered the reason above. Let me know if I could do anything for you. best regards
2

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.

Comments

0

Use onclick event of the anchor tag. this inside href represents current window.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.