Search code examples
javascriptcsspseudo-classdom-events

How to add :hover and click event to element same time?


When I hover parent element his child is appear. When I click parent element his child also appear and when I click it again his child disappear. But then(after clicking parent element for disappearing child) when I hover parent element his child is not appearing. Why?

var parent = document.querySelector('nav > ul > li');
var children = document.querySelector('nav > ul > li > ul');

parent.addEventListener('click', function () {
  if (children.style.display == 'block') {
    children.style.display = 'none';
  } else {
    children.style.display = 'block';
  }
});
nav > ul > li > ul {
  display: none;
}

nav > ul > li:hover ul {
  display: block;
}

li {
  width: max-content;
}

ul {
  padding: 0px;
}
  <body>
    <nav>
      <ul>
        <li><a href="#">Parent</a>
          <ul>
            <li><a href="#">child</a></li>
            <li><a href="#">child</a></li>
          </ul>
        </li>
      </ul>
    </nav>
  </body>

Thanks.


Solution

  • You can easily avoid this by setting children.style.display to the empty string instead of assigning none to it when you want to hide the children.

    EDIT:

    Need a correction: Instead of undefined the empty string needs to be assigned to children.style.display to drop the override (see the text marked in italics - I had to correct that).

    The code snippet should look like this:

    var parent = document.querySelector('nav > ul > li');
    var children = document.querySelector('nav > ul > li > ul');
    
    parent.addEventListener('click', function () {
      alert(children.style.display);
      if (children.style.display == 'block') {
        children.style.display = '';
      } else {
        children.style.display = 'block';
      }
    }, true);