Search code examples
javascripthtmlcssmenumousehover

"touch and feel" at custom HTML drop down menu


I made a custom drop down menu on a HTML page + JavaScript. I want that menu to act as following:

  • When the button "Freunde" gets clicked, the drop down menu appears
  • When the button gets clicked again, the drop down menu disappears
  • When the mouse curor leaves the "area" of button + drop down menu, it disappears

The drop down menu consists of a main div with multiple divs in it (the "menu items").

My first approach was to put a onmouseout() on the main div of the drop down menu, but there is following problem: As soon as I hover over an inner div, the onmouseout() is true, and since the inner divs fill the entire main div, the drop down menu is visible only as long as the user doesn't hover over it.

So I tried it to solve similiarly like a JQuery lightbox, namely to put a "background" div over the whole screen and paste the drop down menu in there, and set the onmouseover() there. That would be almost perfect, but the "Freunde" button is also affected from that.

So is there any way to combine an event from different elements? Like

if(cursor is not over Button && cursor is not over DDMenu)  set invisible

I marked the desired are in following image

enter image description here


Solution

  • Assuming you're set up as

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

    You could set up your CSS like this:

    #nav ul li ul { display: none; }
    #nav ul li.active:hover ul { display: block; }
    

    And then set up your JS like this:

    var menuClick = function() {
        $(this).toggleClass('active');
        menuHover();
    };
    var menuHover = function() {
        $('#nav li.active').hover(function() {
    
        }, function() {
            $(this).removeClass('active');
        });
    });
    
    $('#nav > ul > li').on('click', menuClick);
    

    Granted, this is absolutely gross coding, but I think it should work. (this also assumes you're using the jQuery library).