I am working on a navbar for a website. It contains 3 dropdowns (and a bunch of other stuff I removed to keep the code concise). I want to be able to close the dropdowns by clicking outside of them. I have found many solutions which dealt with this (including the ones on this site), but all of them only accounted for having one such dropdown and I was unable to adapt them to my situation. What I want to achieve is:
If you click one of the buttons, it gets a
is-active
class (which makes its dropdown visible via a sibling selector in CSS) and removes it from all other buttons in the menu.If you click on an open dropdown window, nothing happens.
If you click outside of any dropdown buttons and windows, the
is-active
class gets removed from all the nav buttons that have it.
No matter which recommended solution I tried, one or more of these stopped working as expected. Could anyone help me figure it out?
$('[data-toggle]').click(function() {
var params = $(this).data('toggle');
$(params['target']).toggleClass(params['class']);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-nav__inner" style="height: 100%;">
<div class="main-nav__group d-none d-md-block">
<button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"books\"","class":"is-active"}' data-toggle-target="books">Knihy</button>
<div class="main-nav__dropdown">
// Dropdown contents
</div>
</div>
<div class="main-nav__group d-none d-md-block">
<button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"info\"","class":"is-active"}' data-toggle-target="info">Informácie</button>
<div class="main-nav__dropdown">
// Dropdown contents
</div>
</div>
<div class="main-nav__group main-nav__group--popup">
<button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"profile\"","class":"is-active"}' data-toggle-target="profile">
<i class="icon-left fa fa-user" aria-hidden="true"></i>
</button>
<div class="main-nav__popup">
// Dropdown contents
</div>
</div>
</div>
This code just toggles the dropdowns. My attempts at autoclosing functionality were in separate functions, but I no longer have them, since none of them worked - sorry.
A bonus question: Is there a way of putting the self
keyword into an HTML data-attribute?