← Snippets - Script

Close an Element when Clicking Elsewhere on the Page

In times when you can’t use a clickable overlay, this will close a div when the user clicks anywhere else on the page.

How To

Simply paste the script below into the large function in your script.js. Make sure to update it if needed so it’s targeting the correct items! In the example below, it’s targeting the OLB links.

// When clicking elsewhere on the page, make sure the OLB dropdown is closed
  $(document).click(function(e){
    if( $(e.target).closest(".olb-links").length > 0 ) {
      //User is clicking within the thing that's open, so leave it open.
      //return false;
    }
    else {
      // User is clicking elsewhere, so run stuff to make it close.
      $('.olb-links .dropdown').removeClass('showing');
      $('.olb-links .dropdown-menu').removeClass('show');
    }
  });

Example Sites

Tags: bs2, bs3, bs4, script, close, search