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.
As @Neal says, if you use jQuery, use it properly.
Nevertheless here is an explanation why your code does not work:
this refers to window inside the function. You can set this explicitly by using .call():
<img onclick="getTitle.call(this);" title="myimg" >
<!-- `this` only refers to the element inside the handler -->
or you have to pass the element explicitly as argument:
<img onclick="getTitle(this);" title="myimg" >
Then you have to change your function too:
function getTitle(element) {
alert(element.getAttribute('title'));
}
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 this in 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
<img id="myimg" title="myimg" />
the necessary JavaScript would be:
function getTitle() {
alert(this.getAttribute('title'));
}
document.getElementById('myimg').onclick = getTitle;
This code has to come after the element in the HTML.
you left off a )
function getTitle()
{
alert(jQuery(this).attr("title"));
}
Also since you are using jQuery it might be better to do this:
<img id="imgID" title="myimg" >
jQuery('#imgID').click(function(){
alert(this.title);
})
You forgot the <script></script> tags and you are also missing a ) at the end of the alert() function. You also need to pass this in the onclick function so that you know which item is being called.
<script>
function getTitle(element) {
var objTitle = jQuery(element).attr("title");
alert(objTitle);
}
</script>
<img onclick="getTitle(this);" title="myimg" />
Also, having the <script> before will ensure this particular function works.
Or, to make it even more simpler, you could do this:
<script>
function getTitle(elementTitle) {
alert(elementTitle);
}
</script>
<img onclick="getTitle(this.title);" title="myimg" />