March 12, 2012

Jquery .hover() divs overlapping and wont fade out

Question by Lance Hadley

I’ve been banging away at this and can’t seem to fix this. Ultimately I’m trying to make a drop down nav bar using jquery and divs which reveal by hovering. I’ve almost got it down, but thing is when I have two together and they overlap I can’t get the bottom one to fade out.

Are there any suggestions for how to do this.

<!-- Home Tab -->

<div id="m_bar_home">
  <script src="jquery-1.7.1.js"></script>
  <script>      var hide = false;
     $("#m_bar_home, #m_dddhome").hover(function(){
         if (hide) clearTimeout(hide);
         $("#m_dddhome").fadeIn("fast");
     }, function() {
         hide = setTimeout(function() {
             $("#m_dddhome, #m_ddd_lts").fadeOut("fast");
         }, 250);
     });
     </script> 

  <div id="m_dddhome" >Allo there</div>
  </div>

  <!-- Learn To Sail Tab -->

<div id="m_bar_lts">
  <script src="jquery-1.7.1.js"></script>
  <script>      var hide = false;
     $("#m_bar_lts, #m_ddd_lts").hover(function(){
         if (hide) clearTimeout(hide);
         $("#m_ddd_lts").fadeIn("fast");
     }, function() {
         hide = setTimeout(function() {
             $("#m_dddhome, #m_ddd_lts").fadeOut("fast");
         }, 250);
     });
     </script> 

  <div id="m_ddd_lts" >Allo there</div>

Here is a demo

I think it has something to do with an if function but I’m not sure.

Any ideas?

Answer by Starx

Your coding is very beginner level and very inefficient. I am not trying to offend, but

  1. You are including jQuery twice on same page.
  2. Function call are 100% redundant for both cases. You are writing the same code again and again multiple times.

You should assign a common selector for every div. What if next you have 100 divs, are you going to include 100 jquery files, and same function again and again for each element.

This is how you should do it.

$(".hover").hover(function(){               
    $(this).children(".inner").fadeIn("fast");      
}, function() {    
    $(this).children(".inner").fadeOut("fast");     
});    

See demo

I made some changes to the markup as well to add a common class.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!