Click Outside

Page section: posts

A very common pattern in opening and closing sidebars etc. is where when you click anywhere outside the element you close it. How does this work?

Essentially you create an event listener for the whole document. When clicked a function is run. The first part of the function determines whether the click is inside the element. If so the return keyword is used to end the function.

If not however the next part of the function is run which closes the element.

The code

Here is the code for the left side bar listing the page content on some pages. The sidebar opens because the show-toc class is added to it when the button is pressed.

Therefore to close it again this class is removed.

document.addEventListener('click', (e) => {
  if (e.target.closest('.toc-btn')) return;
  if (e.target.closest('.toc')) return;
  toc.classList.remove('show-toc');
});

How it works

  1. The event listener for the whole page runs an arrow function with the paramenter e for the event itself.
  2. If the event target (the element the event originated from) is the opening button the function ends there with the return keyword.
  3. If the event target is the actual table of contents (ie. the class of toc) then again the function ends there.
  4. If neither of these conditions are met the last line of the function runs and removes the show-toc class from the sidebar.

The closest() method

According to MDN:

The closest() method of the Element interface traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.

MDN

The key thing to note is that this is matching a CSS selector rather than an element defined by a JS variable. And as that could be an HTML tag, a class name or ID name you have to use the . or #.

Keeping the close button

In the example on this site the close button (red box with a cross) is still needed since on small screens the sidebar obfusicates the rest of the page so there is no place to click outside of it.

  1. Techstacker article

Table of Contents