gabitzish
gabitzish

Reputation: 9691

css dropdown menu and javascript

I have this html structure used for a dropdown menu :

<ul>
    <li><ul>...</ul></li>
    <li>...</li>
</ul>

and the css:

li ul {display : none;}
li:hover ul {display : block;}

(this is base structure only).

When I select an item from the menu I'm loading something with ajax and I would like to close the opened submenu.

I've tried with jquery to hide the parent of the clicked element ("li" is the clicked element and "ul" is the parent), the element hides but it does not appear again at mouseover on it's parent. (because the li:hover ul css rule has changed).

Any sugestions about how I could handle this situation?

Upvotes: 0

Views: 501

Answers (4)

Marius Ilie
Marius Ilie

Reputation: 3323

so if you're using javascript after all, you could make the following changes to the css:

li.hover ul {display : block;}

and the javascript:

$("ul li").hover(function(){ 
  $(this).addClass("hover"); 
}, function(){ 
  $(this).removeClass("hover"); 
});

Upvotes: 1

Yorgo
Yorgo

Reputation: 2678

try that menu that i created a couple min ago:

http://jsfiddle.net/aL7Xe/40/

Upvotes: 0

Guffa
Guffa

Reputation: 700840

The reason that it doesn't work is that you hide the element by setting the style on the element itself, and that has higher priority than the style sheet.

Use a class instead of the hover: pseudo-class:

li ul {display : none;}
li.active ul {display : block;}

Set the class on the element when you hover the submenu:

$('ul li').hover(function() {
  $(this).addClass('active');
}, function() {
  $(this).removeClass('active');
});

Now you can remove the class from the element whenever you want, and it will not screw up the hover.

Upvotes: 2

tschoffelen
tschoffelen

Reputation: 520

Best way to solve this is by using Javascript to create the hover effect instead of CSS. This way you can hide the element every moment you want.

So, instead of li:hover ul {display : block;}, use:

$('li').each(function(){
   $(this).bind('mouseover',function(){
      $(this).find('ul').show();
   });
   $(this).bind('mouseout',function(){
      $(this).find('ul').hide();
   });
});

Upvotes: 0

Related Questions