Reputation: 128
I'm having an issue with events not firing in the intended order. I have an event on an input element for focus and focusout. The .focus() shows some content, the .focusout() hides it. I want to be able to .click() on some of the data that I'm showing with the .focus(), however when I click on it, the first thing to fire is the .focusout() event handler, and for some reason the action of hiding the content screws with the .click() event handler.
Here are my event listeners:
$('#content').click(function(evt) {
alert('Yay');
});
$('input').focus(function() {
$('#content').show();
});
$('input').focusout(function() {
$('#content').hide();
});
If any of this is confusing, you can see the exact behavior in this jsfiddle. When you click the input box, the red box shows. But if you then try to activate the click listener on the red box, the .focusout() takes priority and hides the content, and no .click() event transpires.
Desired behavior: Click on input, content shows, click on content, content click listener fires.
Upvotes: 0
Views: 84
Reputation: 1201
Updated-> This is what you want :
$("#content").click(function (evt)
{
if (evt.target == document.getElementById("content"))
{ alert("Yay");
$('#content').show();
$('input').focus();
}
});
$('input').focus(function() {
$('#content').show();
});
$('input').focusout(function() {
setTimeout(function(){ $('#content').hide(); }, 100);
});
This works.
Upvotes: 1
Reputation: 1
Edit, Updated
Try
$('#content').click(function(evt) {
alert('Yay');
});
$('input').focus(function() {
$('#content').show();
});
$('input').on("focusout", function() {
$('#content').delay(100).hide(1);
});
$('#content').click(function(evt) {
alert('Yay');
});
$('input').focus(function() {
$('#content').show();
});
$('input').on("focusout", function() {
$('#content').delay(100).hide(1);
});
#content {
height: 200px;
width: 200px;
display: none;
}
#content {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="content">
</div>
<input type="search">
Upvotes: 0
Reputation: 388326
Try
$('#content').click(function(evt) {
clearTimeout($(this).data('focusTimer'))
});
$(document).click(function(e) {
if ($(e.target).closest('#content').length == 0) {
$('#content').hide();
}
})
$('input').focus(function() {
$('#content').show();
});
$('input').focusout(function() {
var timer = setTimeout(function() {
$('#content').hide();
}, 500)
$('#content').data('focusTimer', timer);
});
#content {
height: 200px;
width: 200px;
display: none;
}
#content {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="content"></div>
<input type="search">
Upvotes: 1