Brack
Brack

Reputation: 333

Hide Div When Clicked

I've got a little HTML/CSS/JQuery drop down menu working. My pseudo code for it is:

function closeMenus() {
  $('.subMenu').css('display', 'none');
}
#mainMenu ul li .subMenu {
  display: none;
  position: absolute;
}
#mainMenu ul li:hover .subMenu {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainMenu">
  <ul>
    <li>
      Menu Header
      <div class="subMenu" onClick="closeMenus();">Menu Content</div>
    </li>
  </ul>
</div>

The CSS works so when someone hovers over Menu Header, the subMenu appears below it and disappears when the mouse leaves the menu. My problem comes when a user clicks an item in the menu; I'd like to hide the menu. The JavaScript hides the menu fine but when the user mouses over the menu header again, it doesn't reappear. It appears that CSS won't override the JavaScript display property. Most, if not all, of the links won't be going to other pages, just calling more JavaScript.

Anyone have any ideas how to hide the sub menu on click so that it will be again visible, or do I need more Javascript to show the menu every time someone hovers?

Upvotes: 1

Views: 478

Answers (4)

bricker
bricker

Reputation: 8941

You're trying to do half of it with CSS and half of it with jQuery. Just do it all with jQuery: http://jsfiddle.net/hw5qr/

$('.subMenu').click(function() {
    $(this).hide();
});

$('#mainMenu').hover(function() {
    $(this).find('.subMenu').show();
}, function() {
    $(this).find('.subMenu').hide();
});

Upvotes: 0

styrr
styrr

Reputation: 829

Like you already said are element styles stronger than css styles (unless you use !important). So you have to to do everything with Javascript what shouldn't be to hard. You have just to register two more event listener: onmouseover and onmouseout. With them you can set the display property to the correct value and it will work this way.

Upvotes: 0

Alex Feinman
Alex Feinman

Reputation: 5563

Use JQuery more fully -- look into the .toggle() command and bind it via click:

$('.subMenu').click(function() {$(this).toggle();});

Then you can eliminate most of your other code.

Upvotes: 1

neworld
neworld

Reputation: 7793

Stryle attribute has highest priority.

$('.ftpBrowseSubMenu').css('display','none');

make

<div style="display:none">

, so rule

#mainMenu ul li:hover 

has lower priority against style attribute. So, you have to do everything with javascript.

Upvotes: 0

Related Questions