I
I
Ilya Filonov2019-05-30 16:00:09
JavaScript
Ilya Filonov, 2019-05-30 16:00:09

How to hide window when clicked outside of it jQuery?

There is a dropdown menu with the class .menu-mobile that is hidden by the bootstrap class d-none.
Opened by clicking on .button.
The problem is to hide it :

a) When clicking on any menu link.
b) When clicking anywhere

I wrote the following JQ code, but it allows you to open on click on .button and close on click on .button or any menu element with the class .m-nav-link.

$('.button, .m-nav-link').click(function() {
    $('.menu-mobile').toggleClass('d-none');
  });


How can I make it close in the same way when clicking on any place except for a div with the .menu-mobile class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Panteleev, 2019-05-30
@s_panteleev

https://codepen.io/anon/pen/XwxOaY

$(document).on('click', function(e) 
{
    var container = $('.menu-mobile');
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question