I have code like this
<img onclick="getTitle();" title="myimg" >
function getTitle()
{
alert(jQuery(this).attr("title");
}
and its not working. Can somebody explain how to do this right. And what is wrong with this code.
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.
As @Neal says, if you use jQuery, use it properly.
Nevertheless here is an explanation why your code does not work:
thisrefers towindowinside the function. You can setthisexplicitly by using.call():or you have to pass the element explicitly as argument:
Then you have to change your function too:
For more information about this type of event handling model, read this article on quirksmode.org about early event handlers.
There is another one which explains
thisin the context of event handlers.The best is if you read all the articles about event handling and learn about the different models. You actually should not bind event handlers through HTML attributes anymore.
For the sake of completeness, without jQuery, a better why is to attach the event handler to the DOM property. Assuming your image has an ID
the necessary JavaScript would be:
This code has to come after the element in the HTML.