0

I have created a dropdown with 2 options, menuitem1 and menuitem2 .But the dropdown is not hiding when I click outside.

As per the click() function, the dropdown is hiding when I click itself. Where should I add $('#listdown').hide('slow') code?

I have written the following code in JavaScript:

$(function(){ 
    $(document).click(function(){
        $('#listdown').hide('slow');
    });
    $("#listdown").click(function(e){
        e.stopPropagation();
    });
});

function click_gearbox(e)
{
    var gear_box = document.getElementById('gearbox');
    gear_box.style.display = 'none';    

    if (gear_box.style.display == "none") {
        // Getting the actually position of the mouse 

        list_down.style.top = e.clientY + 'px';
        list_down.style.left = e.clientX + 'px';
        list_down.style.display ='block';
        gear_box.style.display = 'block';
    }
    $('.dropdown-menu');
}

HTML :

<body>
    <p id="on_body"></p>
    <div id= "gearbox" class="dropdown" >
        <a class="dropdown-menu" data-toggle="dropdown" href="#"></a>
        <ul id = "listdown" class="dropdown-menu" role="menu" aria-labelledby="showgear">
            <li role="presentation"><a role="menuitem1" tabindex="-1" href="#">list1</a></li>
            <li role="presentation" class="divider"></li>
            <li role="presentation"><a role="menuitem2" tabindex="-1" href="#">list2</a></li>      
        </ul>
    </div>
</body>
Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51
Ramya
  • 1
  • 1
  • //showgear is the id if gearbox awesome icon – Ramya Mar 28 '16 at 11:48
  • You should narrow your question, when you want to exactly hide your dropdown? What does it mean by `outside`?See this [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element?rq=1) – Vinoth Krishnan Mar 28 '16 at 11:58
  • Thank you Thomas for your reply. $("body").click(function(e){ if(e.target.className !== "fa fa-cog") { $(".dropdown").hide(); } }); – Ramya Apr 01 '16 at 09:08
  • The following code worked for me. If the target class is not the gearbox and if I click outside the dropdown will hide. Not sure why toggle was not working for me. – Ramya Apr 01 '16 at 09:09

1 Answers1

0

Is seems like you are missing some thing here you have to add dropdown-toggle class if you are using bootstrap.

1) <a class="dropdown-menu" data-toggle="dropdown" href="#"></a>
2) <a class="dropdown-menu dropdown-toggle" data-toggle="dropdown" href="#"></a>
Rahul Pandey
  • 116
  • 6