Stop an div from hiding when clicking page except from close button

Hi there,

I have a link that opens a div full screen and has a close button to hide it. This works fine, but if I click anywhere on the page apart as well as the close button, it closes the div.

This is a fiddle:

(For some reason it is only the buttom half of the page that closes the div in the fiddle, but on the live site, it’s anywhere on the page)

What I am trying to do is only have the close button close the div and not when the user clicks anywhere on the page.

I have tried removing #search from this line, but it doesn’t seem to work.

jQuery(‘#search, #search button.close’).on(‘click keyup’, function(event) {

Any ideas what I need to do?


1 Like

I think this is what you want for that last part.

    jQuery(' #search button.close').on('click keyup', function(event) {       
        if ( == 'close' || event.keyCode == 27) {

That seems to work :slight_smile:


Awesome, thank you, that worked!

1 Like

Here is a version with functional escape key. Could possibly be refactored.

(($) => {

  const openSearchModal = () => {
      .find('form input[type="search"]')

  const closeSearchModal = () => {

  const closeModalHandler = (event) => {
    // exit early if event type is keypress
    // and is not an escape key
    if (event.type === 'keydown' && event.key !== 'Escape') {

    // remove close modal handler from document
    $(document).off('keydown', closeModalHandler);


  const openModalHandler = (event) => {

    // add close modal handler to document
    $(document).on('keydown', closeModalHandler);


  $(() => {
    $('a[href="#search"]').on('click', openModalHandler);
    $('#search button.close').on('click', closeModalHandler);


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.