romeovs
romeovs

Reputation: 5943

continious hover on multiple elements

I have two neighbouring elements $("#video") and $("#progress").

I would like a third element $("#time") to be shown using fadeIn when the mouse enters either one of these elements, and hidden again using fadeOut when the mouse leaves the element. I can get this to work, but there is a small issue.

Whenever the mouse enters one of either elements, coming out of the other, the $("#time") element first gets hidden and than shown again, while I would like it to be shown always.

This jsfiddle demonstrates the issue more clearly.

How can this be fixed?

Note that the elements, although close to each other in the webpage, are actually pretty separated in the code, so it is not possible to put them all together in one big div and put the hover on that div.

Upvotes: 3

Views: 204

Answers (4)

Blake Plumb
Blake Plumb

Reputation: 7199

I know I am late on this one, but I wanted to say that I would check to see if the elements were being hovered over and execute the fadeout if they are not. See fiddle. I also would add the stop() method to avoid multiple animations firing if the user enters and exists the div quickly.

$('.hover').hover(function(){
  $('#time').stop(true,true).fadeIn(300);
},function(){
  setTimeout(function(){
    if($('.hover:hover').length == 0){
        $('#time').stop(true,true).fadeOut(300);
    }
  },0);
});

Upvotes: 3

Hosein
Hosein

Reputation: 581

You can use the setTimeout method for your Fade Out code and with a variable find out that if you should hide that or not.

var ShouldBeShown = false;    
$(".hover").hover(fIN, function(){
  ShouldBeShown = false;
  setTimeout(fOUT, 50);
});
function fIN() {
  ShouldBeShown = true;
  $("#time").fadeIn(300);
}
function fOUT() {
  if(!ShouldBeShown)
    $("#time").fadeOut(300);
}

http://jsfiddle.net/EyFdn/1/

Upvotes: 0

brenjt
brenjt

Reputation: 16297

Try placing a div around the entire block and adding the hover class to it

<div class="hover">
    <div id="video" style="background: green; height: 100px;"> VIDEO </div>
    <div id="progress" style="background:red"> bar </div>

    <div id="time" style="display: none"> 01:35 </div>
</div>

Upvotes: 2

wirey00
wirey00

Reputation: 33661

You can wrap those two elements with another div

<div id='wrapper'>
  <div id="video" style="background: green; height: 100px;" class="hover">VIDEO</div>
  <div id="progress" style="background:red" class="hover">bar</div>
</div>
<div id="time" style="display: none">01:35</div>

then bind the hover to the wrapping div

$("#wrapper").hover(function () {
  $("#time").fadeIn(300);
}, function () {
  $("#time").fadeOut(300);
});

FIDDLE

Upvotes: 4

Related Questions