Detect when container and child elements lose focus with JQuery

11,934

Solution 1

You could try listening on the focusout event and then checking if the current element with focus is a child of your container, like this:

$('#boxA').on('focusout', function (e) {
    setTimeout(function () { // needed because nothing has focus during 'focusout'
        if ($(':focus').closest('#boxA').length <= 0) {
            hideFunction();
        }
    }, 0);
});

Solution 2

Try giving your div a tabindex attribute:

<div id="boxA" tabindex="0">
  <ul>
    <li>x</li>
    <li>y</li>
    <li>z</li>
  </ul>
</div>
<div id="boxB" tabindex="1">
...
</div>

From the docs:

In recent browser versions, the [focus] event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

Share:
11,934
amburnside
Author by

amburnside

Web Developer PHP - Laravel 5.x / Zend framework Ruby on Rails MySQL LAMP / LEMP HTML5 CSS JS JQuery / Bootstrap

Updated on June 09, 2022

Comments

  • amburnside
    amburnside almost 2 years

    I wish to determine when an HTML element and it's children lose focus when the user clicks away from the element. Eg:

    <div id="boxA">
      <ul>
        <li>x</li>
        <li>y</li>
        <li>z</li>
      </ul>
    </div>
    <div id="boxB">
    ...
    </div>
    

    At the moment I have:

    $("#boxA").live('blur', function() { hideFunction();  });
    

    However, this does not work. If I click any element within Box A, it loses focus, but I only want it to happen when Box B is clicked or anywhere else on the page.

    Edit & Solution

    I found this solution on Stack Overflow. It works for me:

    Use jQuery to hide a DIV when the user clicks outside of it

    • VisioN
      VisioN over 11 years
      How can you click away from <div> element? This is not a form field.
  • Ben Everard
    Ben Everard over 11 years
    That is not an answer, this should be a comment against the question.
  • Dimitris Damilos
    Dimitris Damilos over 11 years
    Why is that? I offering an alternative that has worked for me.
  • Gyuri
    Gyuri over 3 years
    Your answer makes you sound like you haven't tried it yourself. If you reword it to something like "This worked for me" it's less misleading.