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?

Thanks!

1 Like

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

    jQuery(' #search button.close').on('click keyup', function(event) {       
        if (event.target.className == 'close' || event.keyCode == 27) {
            jQuery('#search').removeClass('open');
        }
    });

That seems to work :slight_smile:

2 Likes

Awesome, thank you, that worked!

1 Like

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

(($) => {

  const openSearchModal = () => {
    $('#search')
      .addClass('open')
      .find('form input[type="search"]')
      .focus();
  };

  const closeSearchModal = () => {
    $('#search').removeClass('open');
  };

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

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

    closeSearchModal();
  };

  const openModalHandler = (event) => {
    event.preventDefault();

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

    openSearchModal();
  };

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

})(jQuery)
2 Likes

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