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?
focusout() doesn't work for Divs.
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.
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.
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.
$("#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
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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With