简体   繁体   中英

Is there any way to avoid a focusout event when the user switches to an entirely different window?

I'm currently using

$('#input').blur(function(){...

in order to handle the loss of focus on an input in my web application.

It behaves as intended for the most part, except I don't want the event to trigger when the user switches to a different window entirely. I noticed that the blur event is triggered even when I switch to my chrome dev tools. This behavior is unintended. I should also mention that using a focusout event produces the same results.

As an example of what I want, you'll notice that if you search for things on google, there appears to be a focusout event when you click away from the input which makes the suggested searches disappear. However if you click on an entirely different window that isn't your browser, the results will remain on the screen as if the focusout had not been triggered. Is there some way to do this?

Unfortunately, the input's blur is one of the first to trigger, before even the window's one or any visibilitychange event fires.

This means that we need to delay all executions of this input's event in order to be sure that it wasn't cause by the window's blur. To do so, just store a timeout id that you will cancel in window's blur event handler.

 let blur_timeout; window.addEventListener( 'blur', (e) => { clearTimeout( blur_timeout ); // cancel the input's timer } ); document.getElementById( 'inp' ).addEventListener( 'blur', (e) => { // wait a bit so we are sure it's not caused by window's blur blur_timeout = setTimeout( handleInputBlur, 10 ); } ); function handleInputBlur() { console.log( 'input blurred' ); }
 <input id="inp">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM