prime
prime

Reputation: 15594

A way to monitor how the focus out of an element happens in jquery

I'm developing an element group and want to trigger some functionality when an elements' focusout event triggers.

But I have to monitor how the focusout happened, which cause the focus out.

Assume the focusout is bind for element A. if user click on the element B the focusout should call the function_B, if user click on the element C the focusout should call the function_C. And elements B,C should not be inside element A.

pseudo code : 

$( element_A ).focusout(function() {

   element_user_interaction = wether user clicks on element_B or element_C
   if(element_user_interaction == element_B){
        function_B();
   }else if(element_user_interaction == element_C){
        function_C();
   }

});

I found a code from SO. see the accepted answer

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

I tried but could not change the above code to match for the pseudo code.

Upvotes: 1

Views: 183

Answers (1)

Stepashka
Stepashka

Reputation: 2698

You should use the property of the event relatedTarget.

$( element_A ).focusout(function(e) {
   if(element_B.is(e.relatedTarget)){
        function_B();
   }else if(element_C.is(e.relatedTarget)){
        function_C();
   }
});
  • For onfocus and onfocusin events, the related element is the element that LOST focus.
  • For onblur and onfocusout events, the related element is the element that GOT focus.

Warning: This property is null if you click on something other than form elements i.e. image or text. Which is logical but could be confusing.

See more details at http://www.w3schools.com/jsref/event_focus_relatedtarget.asp

Upvotes: 2

Related Questions