views:

85

answers:

4

Hello all,

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.

A: 

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.

Seb
+2  A: 
$('#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

 });
jAndy
The hover worked for me! How would I unbind the hover? I tried `$('#row-img_1').unbind('hover');` but it did not work.
Abs
Thanks to Nicks comment, I unbind the mouseenter and mouseleave instead of the usual. I could of probably have worked that out from your answer. Thanks jAndy.
Abs
@Abs - `.unbind('mouseenter mouseleave')` :)
Nick Craver
A: 
$('#row-img_1').mouseover(function() { 
    alert('foo'); 
});
Darin Dimitrov
-1 : I think you mean `.mouseover`, not `.onmouseover`
Eric
@Eric, yes you are correct, that's what I meant :-)
Darin Dimitrov
+3  A: 

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.

Eric
+1 - It's worth noting that this is not *equivalent*, but *similar* to [`.hover()`](http://api.jquery.com/hover/). It maps to `mouseenter` and `mouseleave`, not `mouseover` and `mouseout`.
Nick Craver
Good point. More often than not, `mouseenter` and `mouseleave` are what is needed for applications like these, anyway.
Eric
@Nick - that is useful to know!
Abs