Handle blur event of parent element fired by focus on child element and by clicking outside of child

Umesh K. picture Umesh K. · Jan 19, 2016 · Viewed 11.9k times · Source

I have a "parent div" containing a child box input type=number. When user clicks outside of input box I use blur or focusout event of parent div to use input values at some other place.

I also need to use $('inputbox').trigger('focus') at some place, which fires "parent div"'s blur event unwantedly and runs code on that event.

Please give a solution to stop this parent blur event on child's focus OR give a way to find whether focus is made by trigger('focus') on child element or by user clicking outside of parent div.

I need to fire parent Blur only when user clicks outside of it & not when focus is triggered through code.

Answer

Scott Selby picture Scott Selby · Jan 19, 2016

with jquery you can make custom events very easily , something like:

$('inputbox').trigger('special-focus');

then you can wait for this event just like any other event:

$('div').on('special-focus' , function(){ ... } );

this will prevent your events from interfering with the built in ones.

I guess if you don't want to use that suggestion then do this in your click handler or your focus handler of the child

 .on('focus' , function(e){
    e.stopPropagation();
    e.preventDefault();
   /// the rest of your code ...
 });

this will stop the propagation of events to parent elements