Paultwo
Paultwo

Reputation: 11

how do you prevent the mouseout of a parent from firing when hovering onto its child element?

So let's say I have a red square image that turns green when the mouse goes over it, and it turns back to red when the mouse leaves the square. I then made a menu sort of thing with it so that when I hover on the square, it turns green and a rectangle appears below it.

What I want to happen is this: After the rectangle appears and I move the mouse out of the square and over the rectangle, I want the square to remain green until I move the mouse out of the rectangle.

How do I do this with jquery? The code i use is something like this:

$('.square').hover(function() {
    $(this).addClass('.green'); 
    }, function() {
    $(this).addClass('.red');
});
$('.square').hover(function() {
    $(this).children('.rectangle').show(); 
    }, function() {
    $(this).children('.rectangle').hide();
});

Upvotes: 1

Views: 1258

Answers (3)

Matteo Riva
Matteo Riva

Reputation: 25060

I have recently had the same problem. What I did was adding an mouseenter event to the "child" element too so while passing from parent to child it's not turned off. Basically I have mouseenter and mouseleave on both elements (which of course are slightly overlapping for this to work).

Upvotes: 1

mck89
mck89

Reputation: 19241

If the menu is inside the square you can try something like this:

$('.square').bind("mouseenter",function(){
   $(this).addClass('green');
   $('.rectangle').show();
});

$('.square').bind("mouseleave",function(){
   $(this).addClass('red');
   $('.rectangle').hide();
});

Upvotes: 0

Doug Neiner
Doug Neiner

Reputation: 66191

You have just a few errors in your code.

  1. You never remove any classes, you only try adding classes. This will only work once, and all subsequent tries won't do anything since jQuery will not add the same class twice to the same element.
  2. You shouldn't use the dot syntax when adding classes. Just supply the class name by itself:

jQuery:

$('.square').hover(function() {
    $(this).addClass('green'); 
    $(this).children('.rectangle').show(); 
}, function() {
    $(this).removeClass('green');
    $(this).children('.rectangle').hide();
});

CSS:

/* Make sure .green comes after .red */
.red { background: red }
.green { background: green }

Upvotes: 2

Related Questions