jQuery: Click Anywhere But Some Element

jquery-logo-post-headerPicture it. I have a clickable main navigation. This click expands a sub-menu. It’s all styled and looks great. However, if you click outside of an already expanded sub-menu, said sub-menu is still shown.

So the problem is I need to attach an event to a click anywhere but my main navigation. Simple? I did a little searching and found this article over at StackOverflow. The solution is not only simple, but elegant as well.

Consider this jQuery

$(document).click(function(e) {
  if ( $(e.target).closest('.navigation').length === 0 ) {
    // hide menu here
  }
});

I had not heard of the jQuery .closest() method before today. Not sure how I missed it, but it’s an incredibly useful tool. It crawls up the DOM looking for the next “closest” element with the passed in selector. If it finds it you’ll have a list with one element, if not you’ll have a list with no elements.

So the code above tests to see if our .navigation was somewhere up the DOM from our currently clicked target element. If it didn’t find it, then a click occurred outside the navigation, therefore we’ll need to call code to retract all sub-menus. If it did find it, well that means a click occurred inside the main navigation somewhere and our reset code will be ignored.

Read up on .closest() right here.

Posted in: Development  |  Tagged with: ,  |  Leave a comment
3 comments on “jQuery: Click Anywhere But Some Element
  1. Excellent tutorial, just what I was looking for!

  2. Tonyshin says:

    Thanks! This is actually what I am looking for solving the dropdown block problem.

Leave a Reply to jibran Cancel reply