Cam
Cam

Reputation: 1902

Jquery Hover show/hide issue

Im trying to setup so that when you hover over class .object1 -> in turn should reveal .obj_1 when you are not hovered on it, it should hide .obj_1. I may be a little off in my code, thanks for the help!.

$(document).ready(function() {   
  $(".obj_1 , .obj_2").hide();
      });
      $(".object1").hover(
        function() { $(".obj_1").show(); },
        function() { $(".obj_2").hide(); }
   );
      $(".object2").hover(
        function() { $(".obj_2").show(); },
        function() { $(".obj_1").hide(); }
   );

Upvotes: 0

Views: 748

Answers (1)

guy mograbi
guy mograbi

Reputation: 28608

Very simple it should be

$(document).ready(function() {   
  $(".obj_1 , .obj_2").hide();
      });
      $(".object1").hover(
        function() { $(".obj_1").show(); },
        function() { $(".obj_1").hide(); }
   );
      $(".object2").hover(
        function() { $(".obj_2").show(); },
        function() { $(".obj_2").hide(); }
   );

The "hover" handler function signature is ( mouseInHandler, mouseOutHandler). For object1 you want to show obj_1 on mouseIn, and hide it on mouseOut. You don't need to reference obj_2 on object1 hover handlers.

Check out the fiddle I made here

FYI - the hover events act weird when you have complex inner content. ( for example, div within another div and so on ). I advise you to use "mouseenter" and "mouseleave"

UPDATING ANSWER AFTER REALIZING THIS IS A DROP DOWN MENU QUESTION

The drop down menu in CSS is a great example where "hover" won't suffice --> because the submenu disappears once you're not on the link anymore.. and that's not what we want.

It is important to note 3 things about drop down menus :

  1. They can (?should?) be achieved purely with CSS
  2. The HTML structure is important.

For example, consider the following structure instead :

<ul class="menu">
    <li>
    </li>
    <li>
        <ul class="menu">
         <li>
         </li>
        </ul>
    </li>
</ul>

This structure is recursive - you can have infinite levels of submenus - and the mouseenter/mouseleave on the "li" will hold since the submenu is part of the "li" item.

To see this in action have a look in my fiddle

Please also note that I removed the first "hide" from the onload code, and replaced it with css "display:none" - which resolves flickering on page load ( flickering means - first the submenu shows, and once the page loads, we hide it. )

A css solution would include a selector with "hover" on it ( yes, hover.. )

You can find plenty of blog posts about it while searching in google.

Here is the first one I found.

Upvotes: 1

Related Questions