Search code examples
jqueryeventsdrop-down-menuevent-bubblingstoppropagation

Hiding menu by clicking any where in the page


I have this code but it seems that it always fire the event attached to 'html', because when i click on the .optTrigger then menu shows, and click on it again, it does that flickering thing, it hides the menu for a second and shows it again, so i guess it fires the 'html' click event.


Try it : here's the site uploaded, you have to add a new task, and click on the options trigger, it's the arrow button next to the check button in the new task, far right. HERE


Here's my code :

html:

<div class="mainTaskWrapper clearfix">
    <div class="mainMarker"></div>
    <label class="mainTaskLabel"></label>
    <div class="mainHolder"></div>
    <div class="subTrigger opened"></div>
    <div class="checkButton"></div>
    <div class="optTrigger"></div>
    <div class="addSubButton"></div>
    <div class="dateInfo"></div>
    <div class="mainOptions">
        <ul>
            <li id="mainInfo">Details</li>
            <li id="mainEdit">Edit</li>
            <li id="mainDelete">Delete</li>
        </ul>
    </div>
</div>

script:

$("#tasksWrapper").on("click", ".mainTaskWrapper .optTrigger", function(evt){
    $(this).siblings(".mainOptions").fadeToggle(100);
    $(this).toggleClass("active");
    evt.stopPropagation();      
});

$("html").on("mousedown",function(){            
    $(".optTrigger").siblings(".mainOptions").hide();
    $(".optTrigger").removeClass("active");
});

Solution

  • The problem is in attaching event handlers of different types to the DOM elements:

    $("#tasksWrapper").on("click", ...
    ...
    $("html").on("mousedown", ...
    

    Even though propagation of the click event is prevented a click will also fire mousedown event.

    So instead of $("html").on("mousedown", ... better do $("html").on("click", ...