Ian Robinson Ian Robinson - 4 months ago 36
jQuery Question

How can I cancel hoverIntent on parent element when hoverIntent on child element fires?

I have a parent element that when hovered over shows an element. I also have a child element that when hovered over shows a different element.

I don't want them both to fire at the same time - i.e. if you're hovering over the child I only want to show it's associated element - and suppress the hovering over of the parent element.

I'm having trouble getting this to work reliably. Probably missing something obvious. Any ideas?

Edit - clarification:

The "parent" and the "child" in this case are separate reusable components that don't know about each other, so I can't actually inject the context from one into the other

Here is the demo I've set up using jQuery & the hoverIntent plugin.

HTML:

<div id="parentBar">
<ul id="childMenu">
<li>Menu 1</li>
</ul>
</div>

<div id="barInfo">
<p>This is shown when hovering overing inside of the parent bar.</p>
</div>

<div id="menuInfo">
<p>This is shown when hovering over inside of the child menu.</p>
</div>


CSS:

#parentBar{width:500px;border:solid 1px black;}
#childMenu{margin-left:10px;padding-left:10px;width:100px;border:solid 1px green;}
#menuInfo, #barInfo{display:none;}


JavaScript:

$('#parentBar').hoverIntent({
//interval: 500,
over: function(e) {
$('#barInfo').show();
},
out: function(e) {
$('#barInfo').hide();
}
});

$('#childMenu').hoverIntent({
//interval: 250,
over: function(e) {
$('#menuInfo').show();
},
out: function(e) {
$('#menuInfo').hide();
}
});

$('#childMenu').bind('mouseenter', function(e){
e.stopPropagation();
});


You can view it here on jsFiddle: http://jsfiddle.net/hNqQ7/1

Answer
var flag = false;
$('#parentBar').hoverIntent({
  interval: 500,
  over: function(e) {
    if(!flag) {
        $('#barInfo').show();
    }
  },
  out: function(e) {
    $('#barInfo').hide();
  }
});

$('#childMenu').hoverIntent({
  interval: 250,
  over: function(e) {
    $('#menuInfo').show();
  },
  out: function(e) {
    $('#menuInfo').hide();
  }
}).mouseenter(function(){
    flag= true;
}).mouseleave(function(){
    flag = false;
});