Doahh Doahh - 5 months ago 39
CSS Question

CSS: menu open on hover and close on click

I have a

<li>
that when
hovered
open a
<ul>
.

I would like to be able to also click the
<li>
and have the
<ul>
open and close but still keep the hover functionality. At the moment once the click occurs I lose the
:hover
.

JSFiddle

CSS

ul#popup-menu {
display: inline-block;
margin: 0;
cursor: pointer;
}
ul#popup-menu ul {
display: none;
position: absolute;
left: 0;
top: 100%;
margin: 0;
}
ul#popup-menu li {
list-style-type: none;
position: relative;
}
ul#popup-menu li:hover > * {
display: block;
}


HTML

<ul id="popup-menu">
<li>
Click to open
<ul>
<li>
Item 1
</li>
<li>
Item 2
</li>
<li>
Item 2
</li>
</ul>
</li>
</ul>


JavaScript

$(document).ready(function() {
$('#popup-menu').click(function() {
var element = $('ul#popup-menu ul')
if (element.css('display') === 'block') {
$('ul#popup-menu ul').css('display', 'none');
} else {
$('ul#popup-menu ul').css('display', 'block');
}
});
});

Max Max
Answer

Add code that resets style attribute, because inline-style has higher priority that ul#popup-menu li:hover > * css selector. So when style is set display-block is always none;

Try this:

$(document).ready(function() {
  $('#popup-menu').click(function() {
    if ($('ul#popup-menu ul').css('display') === 'block') {
      $('ul#popup-menu ul').css('display', 'none');
    } else {
      $('ul#popup-menu ul').css('display', 'block');
    }
  });

  $('#popup-menu > li').mouseleave(function() {
    $('ul', this).removeAttr('style');
  })
});

Fiddle

So when you mouseleave the menu header it goest to nested UL and remove style attribute, so hover works again

Comments