Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Hide/Show with Slide on Hover... better way to do this?

Basically having some trouble with using Hover to hide or show an item.

The idea is simple, on hover show a div. When no longer hovering, hide it. Problem is if the mouse hovers over the div and leaves too quickly, the show/hide div will stay visible. I'm hoping this is something easily remedied and not a typical problem with the hover event.

 jQuery
 (
   function() 
   {
     jQuery(".slideDiv").hide();

     jQuery(".mainDiv").hover
     (
       function() 
       {
         var children = jQuery(this).children(".slideDiv");

         if (children.is(":hidden")) 
         {
           children.show("slide", { direction: "left" }, 100);
         }
       },
       function() 
       {
          var children = jQuery(this).children(".slideDiv");
          children.hide("slide", { direction: "left" }, 100);
       }
     );
   }
 );

Styles look like:

 .mainDiv
 {
   margin:5px;
   height:200px;
 }

 .slideDiv
 {
   background-color:Teal;
   float:left;
   height:200px;
   position:absolute;
   z-index:100;
 }

And markup

    <div class="mainDiv">
        <div class="showDiv">
            Hover me
        </div>
        <div class="slideDiv">
            Do you see me?
        </div>
    </div>
    <div class="clear"></div>
    <div class="mainDiv">
        <div class="showDiv">
            Hover me too
        </div>
        <div class="slideDiv">
            Do you see me now?
        </div>
    </div>
like image 511
Programmin Tool Avatar asked Jul 09 '09 18:07

Programmin Tool


2 Answers

Use the hoverIntent plugin. This avoids anything being shown if the user simply passes the mouse over the elements, and avoids an unsightly chain of animations.

like image 60
redsquare Avatar answered Nov 11 '22 01:11

redsquare


I tried your script and it did as you described. I tried removing the children.is(":hidden") from your script, but the problem still occurred.

When I rewrote it the script the div never stays visible. So, it appears that the problem is with using jQuery's children instead of find to get to the object:

Still has problems:

 jQuery (
   function(){
     jQuery(".slideDiv").hide();
     jQuery(".mainDiv").hover (
       function() {
         $(this).children(".slideDiv").show("slide", { direction: "left" }, 100);
       },function(){
         $(this).children(".slideDiv").hide("slide", { direction: "left" }, 100);
       }
     );
   }
 );

Works as intended:

 $(document).ready(function(){
   $('.slideDiv').hide();
   $('.mainDiv').hover(
     function(){
       $(this).find('.slideDiv').show('slide', { direction: 'left' }, 100)
     },
     function(){
       $(this).find('.slideDiv').hide('slide', { direction: 'left' }, 100)
     }
   )
 })

And yes, The hoverIntent plugin is nice :P

like image 40
Mottie Avatar answered Nov 11 '22 02:11

Mottie