Sunday 20 October 2019

javascript - Close menus when clicking outside

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:




  1. 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.


  2. If you click on an open dropdown window, nothing happens.


  3. 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']);
})








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?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...