Search code examples
javascriptjquerydrop-down-menuonmouseoveronmouseout

drop down menu on mouseout should remain visible


The button with dropdown menu should be visible when the mouse is moved inside the div which works fine but the problem is that when I move the mouse out of that div, I want the button and dropdown menu to remain visible if menu is dropped down but the button should get hidden if menu is not dropped down.How can I achieve this?(in the given code, button and dropdown menu get hidden on mouseout no matter what)

<div id="img_container" name="img_container" onmouseover="f()" onmouseout ="g()">
            <img src="image/images.jpg"  alt="Cover" >
            <div class="btn-group" id="cov" name="cov" >
               <button  class="btn dropdown-toggle" data-toggle="dropdown">Action
               </button>
               <ul class="dropdown-menu">
    <!-- dropdown menu links -->
                <li><a href="#">Secondary link</a></li>
            <li><a href="#">Something else here</a></li>
            <li class="divider"></li>
            <li><a href="#">Another link</a></li>
               </ul>
            </div>
        </div>


function f(){
      document.getElementById("cov").style.display="inline-block";
  }

  function g(){
      document.getElementById("cov").style.display="none";
  }

Fiddle


Solution

  • If I am understanding you correctly you want something like this:

    var list = document.getElementById("dropdown-menu");
    var menu = document.getElementById("cov");
    
    function dropdown() {
        if (list.style.display == "none") {
            list.style.display = "block";
        } else {
            list.style.display = "none";
        }
    }
    
    function f() {
        menu.style.display = "block";
    }
    
    function g() {
        if (list.style.display == "none") {
            menu.style.display = "none";
        } else if (list.style.display == "block"){
            menu.style.display = "block";
        } else {menu.style.display = "block"}
    }
    

    Here is a DEMO