Jeanluca Scaljeri
Jeanluca Scaljeri

Reputation: 29107

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 divs 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 ?

Upvotes: 1

Views: 894

Answers (1)

hoangdv
hoangdv

Reputation: 16127

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.

Upvotes: 1

Related Questions