SeattleAls SeattleAls - 6 months ago 7
Javascript Question

Add 'title' attribute to an element (using event)

This is my code in HTML:

<img id="test" src="https://blah">


This is in my jQuery and it works:

$( document ).on( 'mouseover', 'img', function(e) {
}


How can I add attribute to this 'img' element? I want this:

<img id="test" src="https://blah" title='test'>


I tried:

e.attr('title', 'test');
e.prop('title', 'test');
this.attr('title', 'test');
$(this).attr('title', 'test');
this.prop...


so on and so on.

Answer

You can use the hover() method:

$('img').hover(function() {
    $(this).attr('title', 'test');
});

In this case, $(this) represents the image that has been hovered over.

You can also do:

$('img').hover(function(e) {
    $(e.currentTarget).attr('title', 'foo');
});

In this case, $(e.currentTarget) represents the image that has been hovered over.

Comments