Abs
Abs

Reputation: 57926

Set the mouseover Attribute of a div using JQuery

I would like to set an attribute for a div. I have done this:

$('#row-img_1').onmouseover = function (){ alert('foo'); };
$('#row-img_2').onmouseout = function (){ alert('foo2'); };

However, the above has not worked, it does not alert when mouse is over or when it moves out.

I have also tried the $('#row-img_1').attr(); and I could not get this to work either.

I am aware that I should be using a more effective event handling system but my divs are dynamically generated. Plus this is a small project. ;)

Thanks all for any help.

Upvotes: 0

Views: 4403

Answers (4)

Eric
Eric

Reputation: 97601

You need to bind the event function to the element. Setting the event attributes has no effect, as they are interpreted only when the page is loading. Therefore, you need to connect the event callback in a different manner:

$('#row-img_1').mouseover(function() {
    alert('foo');
});
$('#row-img_2').mouseout(function() {
    alert('foo2');
});

In jQuery, there are two more events: mouseenter and mouseleave. These are similar, but mouseenter does not fire upon moving the mouse from a child element to the main element, whereas mouseover will fire the event again. The same logic applies to mouseleave vs mouseout.

However, jquery provides a shortcut for this kind of usage: the .hover method.

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

$('#row-img_1').mouseover(function() { 
    alert('foo'); 
});

Upvotes: 0

jAndy
jAndy

Reputation: 236032

$('#row-img_1').bind('mouseenter', function(event){
    // event handler for mouseenter
});

$('#row-img_1').bind('mouseleave', function(event){
    // event handler for mouseleave
});

or use jQuerys hover event which effectivly does the same

 $('#row-img_1').hover(function(){
    // event handler for mouseenter
 }, function(){
    // event handler for mouseleave

 });

Upvotes: 1

Seb
Seb

Reputation: 25147

Events are registered as functions passed as attributes, like this:

$('#row-img_1').mouseover(function (){ alert('foo'); });
$('#row-img_2').mouseout(function (){ alert('foo2'); });

Also, note the missing on from the onmouseover.

Upvotes: 0

Related Questions