Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery focusout for entire div and children

I have a div that I am creating dynamically via jQuery with some links/buttons in it. When this div loses focus I need to remove it. This part I can do ok.

However, right now I have the focusout event on the wrapper for the div and when I click on a button inside the div, the wrapper loses focus to the child and my event gets fired. Checking if the element clicked is a child of the wrapper I can do, but since the wrapper no longer has focus, my event will not fire again to remove the div.

I have also tried .blur, but this doesn't work any better.

What is the best way to do this?

like image 310
Helto Avatar asked Mar 12 '13 18:03

Helto


People also ask

Can we use Focusout for Div?

focusout() doesn't work for Divs.

How to use focusout function in jQuery?

jQuery focusout() MethodThe focusout() method attaches a function to run when a focusout event occurs on the element, or any elements inside it. Unlike the blur() method, the focusout() method also triggers if any child elements lose focus. Tip: This method is often used together with the focusin() method.

What is the difference between jQuery Focusout () and Blur () events?

The focusout event fires when an element is about to lose focus. The main difference between this event and blur is that focusout bubbles while blur does not.

Which Javascript event is called when an element loses its focus?

The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field). Tip: The onblur event is the opposite of the onfocus event. Tip: The onblur event is similar to the onfocusout event.


2 Answers

$("#yourDiv").focusout(function () {
   if ($(this).has(document.activeElement).length == 0) {
       // remove div
   }
});

$(this) = the div you're focusing out of.

document.activeElement = the element that is currently in focus.

$(this).has(document.activeElement) is simply checking if the active element is a child of your div

like image 141
Isaac Avatar answered Sep 24 '22 13:09

Isaac


here is how I solved this for a menu using event.relatedTarget , :

$('#mapmenu  a.nolink').click(function (e) {//ul.lev-0 > li.expanded >
  $(this).closest('li').toggleClass('hovered');
  e.preventDefault();
  e.stopPropagation();
  return false;
});
$('#mapmenu  a.nolink').closest('li').focusout(function (e) {
  var ax = e.relatedTarget;
  var bx = $(ax).closest('ul');
  if ($(this).has(bx).length == 0) {
    $(this).removeClass('hovered');
  }
});
like image 22
GZveri Avatar answered Sep 23 '22 13:09

GZveri