3 min read

Close dropdowns by clicking outside of them with jQuery

Now that the web is focusing more on click events than hover, this presents a new set of challenges for front end designers. It’s relatively easy with jQuery to show an element when clicking on a trigger and hiding it again using the .toggle method - here’s a quick example.

$('#trigger').click(function() {
  $('#drop').toggle();
});

In order to hide the menu when clicking anywhere else in the document there are a few options. One of which is a jQuery plugin called outside events by Ben Alman which takes all the hard work away. If you’d like to learn the harder way then keep reading.

When you click on a link, the event bubbles up through all of the dom elements which contain that element until it hits the highest level which is $(document). So you need tell the script that every time there is a click on the $(document), the dropdown should close.

$(document).click(function() {
  $('#drop').hide();
});

If you look at this now applied to the previous code you will see that we have broken the dropdown. Don’t worry, this is the expected behaviour. What’s happening is that when you click on the trigger, the $(document) level click event trumps everything else and is applying the .hide() method to an already hidden element. So it doesn’t show.

The final piece to the puzzle is to tell the script to stop the click event from bubbling up when we click on the trigger. This means it will never reach the $(document) level and won’t trigger the .hide() method. To do this, you need to add two things to the original function. You need to add a way to track the click event and then tell that click event not to bubble.

$('#trigger').click(function(event) {
  event.stopPropagation();
  $('#drop').toggle();
});

If you want to look at what the event is then add in console.log(event); and look in the console tab of Firebug or Chrome Inspector.

Now that’s in place, you can see that the dropdown now opens and closes as it did before but now, it also closes when you click anywhere else on the page. So when put together, the final code looks like this:

$('#trigger').click(function(event) {
  event.stopPropagation();
  $('#drop').toggle();
});

$(document).click(function() {
  $('#drop').hide();
});

Once you understand the concept, you can go further by controlling the dropdown behaviour with classes.

See the Pen Close dropdowns by clicking outside of them by Craig Dennis (@craigmdennis) on CodePen.

Posted