简体   繁体   中英

Blur event triggered when child gets focus

I need to perform some action when and item loses its focus.

Basically I have something like this:

<div tabindex="1">
    <h1>title 1</h1>
</div>

<div tabindex="2">
    <h1>title 2</h1>

    <textarea></textarea>
</div>

JS:

$('div').blur((e) => { console.log('blur');});

DEMO

Now, when you switch between div s it works like a charm, but when the second div has focus, and you click the child-textarea a blur event is triggered. This is not what I want, because we're still inside the same div. How can I fix this such that only a blur event is triggered when the click is outside the div ?

a element has been focus then the last element focused will trigger event 'blur'. You may have to design a hack for it...something like:

$('div').blur((e) => {
    setTimeout(function() {
        if(!$('textarea').is(':focus')){
            console.log('blur');
        }
    }, 100);
});

setTimeout is important because blur event being trigged in the first then focus event.

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