Question: 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.

Answer: 
[As @Neal says](https://stackoverflow.com/questions/6496217/using-this-in-javascript-function/6496233#6496233), 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()`**](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/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](http://www.quirksmode.org/js/events_early.html). 

[There is another one](http://www.quirksmode.org/js/this.html) which explains `this` in the context of event handlers.

The best is if you read [all the articles about event handling](http://www.quirksmode.org/js/introevents.html) 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 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" />

```