Search code examples
cssdropdown

close css hover dopdown menu after click on item


I'm using pure css dropdown menu. But after clicking the menu item, the dropdown menu is alway displayed. It will be hidden when I give my mouse out of the menu. How can I close the pure css hover dropdown menu after clicking on the menu item? Thanks for your advice. Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Show Hide Dropdown Using CSS</title>
<style type="text/css">
    ul{
        padding: 0;
        list-style: none;
        background: #f2f2f2;
    }
    ul li{
        display: inline-block;
        position: relative;
        line-height: 21px;
        text-align: left;
    }
    ul li a{
        display: block;
        padding: 8px 25px;
        color: #333;
        text-decoration: none;
    }
    ul li a:hover{
        color: #fff;
        background: #939393;
    }
    ul li ul.dropdown{
        min-width: 100%; /* Set width of the dropdown */
        background: #f2f2f2;
        display: none;
        position: absolute;
        z-index: 999;
        left: 0;
    }
    ul li:hover ul.dropdown{
        display: block; /* Display the dropdown */
    }
    ul li ul.dropdown li{
        display: block;
    }
</style>  
</head>
<body>
    <ul>
        <li>
            <a id="product" href="#">Products</a>
            <ul class="dropdown">
                <li><a onClick="document.getElementById('product').innerHTML = 'Laptop selected!'; return false;" href="#">Laptops</a></li>
                <li><a href="#">Monitors</a></li>
                <li><a href="#">Printers</a></li>
            </ul>
        </li>
    </ul>

</body>
</html>   

Solution

  • Here is a fiddle for you: https://jsfiddle.net/6a3xogfj/2/

    What I did was adding classes to distinguish .open and .closed dropdown status.

    CSS

    ul li ul.dropdown.closed { display: none; }
    ul li ul.dropdown.open { display: block; }
    

    The rest was done via jQuery.

    JS

    $('a#product').on('mouseover', function() {
    
      $(this).siblings('ul.dropdown').removeClass('closed').addClass('open');
    });
    
    $('ul.dropdown a').on('click', function(e) {
    
      e.preventDefault();
    
      $(this).closest('ul.dropdown').removeClass('open').addClass('closed');
      $('section').removeClass('active').filter( $(this).attr('href') ).addClass('active');
      $('a#product').text( $(this).text() + " selected!");
    });
    

    When you hover the menu item #product the dropdown is set from .closed to .open and therefore shown. As soon as a dropdown item is clicked those classes are reset to close the dropdown.