Max Koretskyi
Max Koretskyi

Reputation: 105479

.blur() and .click() events overlapping

I have an editable element that I'm tracking .blur() event on to make it not editable. I also have another element that is supposed to act as 'OK' button signifying that a user finished editing. Here is the HTML (#input is editable element, #ok is OK button):

<div id='container'>
    <span id='input' contenteditable='true'></span>
    <a href="#" id='ok'></a>
</div>

And CSS:

#container {
    border: 1px solid black;
    width:100px;
    position:relative;
}
#input {
    display: inline-block;
    width: 80px;
}
#ok {
    display: inline-block;
    width: 20px;    
    height: 20px;    
    background: green;
    cursor:pointer;
    position: absolute;
    right: 0;
}

I've got two events bound:

$('#ok').click(function(){alert('it is clicked')});
$('#input').blur(function(){alert('blur is detected')});

But whenever I click on the OK button, the .blur() event is triggered, which is not the behavior I want. Besides, after I'm notified about .blur() event I am not notified about .click() event which I assume should happen because this is the next event in events stack. Is possible to avoid getting .blur() event if clicked on the button? Here is the jsFiddle representing the case.

Upvotes: 1

Views: 855

Answers (3)

Liam Allan
Liam Allan

Reputation: 1115

maybe try $('#container').blur(function(){alert('blur is detected')});

Upvotes: 1

Sergio
Sergio

Reputation: 28837

This will work:

$('#input').focus();
$('#ok').click(function () {
    alert('it is clicked')
});
var over_click;
$('#ok').mouseenter(function () {
    over_click = true;
}).mouseleave(function () {
    over_click = false;
});
$('#input').blur(function () {
    if (!over_click) {
        alert('blur is detected')
    }
});

Demo here

Upvotes: 1

Simon Davies
Simon Davies

Reputation: 3686

Have alook at this at it should solve your issue. Stackoverflow Answer

Basically as soon as you try to come out of the input box then blur is going to trigger, once you press ok then you can click the button, but the link above will show you how to solve this issue

Upvotes: 1

Related Questions