Search code examples
javascripthtmldropdown

Stuck on dropdown.js


$(function(){
    // Show hide popover
    $(".dropdown").click(function(){
        $(this).find(".dropdown-menu").slideToggle("fast");
    });
});
$(document).on("click", function(event){
    var $trigger = $(".dropdown");
    if($trigger !== event.target && !$trigger.has(event.target).length){
        $(".dropdown-menu").slideUp("fast");
    }            
});

This is my js for dropdown, and when I click on a few (I have multiple) it doesn't close the previous one and I need it to do so, otherwise it'll get flooded with dropdown menus.

I'm still learning js so I run into a few bumps here or there.


Solution

  • The general idea with this sort of thing is to listen for clicks and close your dropdown(s) if the click did not come from the dropdown itself or any of its child elements.

    For this you can use closest().

    $(() => {
        $(".dropdown").on('click', () => {
            $(this).find('.dropdown-menu').slideToggle('fast');
        });
        $('body').on('click', event => {
            if (!$(event.target).closest('.dropdown').length)
                $('dropdown-menu').slideToggle('fast');
        });
    });