I am searching for the best way to remove the active state from a dropdown menu that appears when a user clicks a certain button. I use jQueries toggleClass method to show/hide the menu on click. But what about removing the active class when the user clicks somewhere else on the page? I prepared a jsfiddle for you to illustrate my question: http://jsfiddle.net/RU83L/.
A solution that comes to my mind is to always remember the last element clicked. Then I could use $(document).click() to remove my “active” class from the element clicked lately. I am just wondering whether there is a cleaner solution?
Well, instead of going through all the trouble to remember the last item clicked, why not just check to see if any element is currently active, then hide as necessary? It is a quick and dirty, but effective method.
That is indeed a better solution than remembering the last element clicked. Thank you kgscott.
I adapted your solution so a click on the document removes the “active” class on the button. You have to keep event bubbeling in mind though. Without event.stopPropagation(); both handlers would be fired in sequence, resulting in an immediate removal of the active class (document handler is fired second) just after its addition (button handler is fired first).
Hm, maybe I misunderstood what jQuery() actually does. I thought it searches the DOM using the given selector and returns a set of fitting jQuery objects. If that is true $('.dropdown-button.active').hasClass("active") will cause a search in the DOM just as $('.dropdown-button.active').removeClass("active") does. So a DOM search will be performed in both solutions when a click on the document is registered (in your example even twice).