I'm trying to show up a container if a input field gets the focus and - that's the actual problem - hide the container if focus is lost. Is there an opposite event for jQuery's focus?
Some example code:
<input type="text" value="" name="filter" id="filter"/>
<div id="options">some cool options</div>
<script type="text/javascript">
$('#options').hide();
$('#filter').focus(function() {
$('#options').appear();
});
</script>
And what I'd like to do is something like this:
$('#filter').focus_lost(function() {
$('#options').hide();
});
This question is related to
javascript
jquery
focus
jquery-events
blur event: when the element loses focus.
focusout event: when the element, or any element inside of it, loses focus.
As there is nothing inside the filter element, both blur and focusout will work in this case.
$(function() {
$('#filter').blur(function() {
$('#options').hide();
});
})
jsfiddle with blur: http://jsfiddle.net/yznhb8pc/
$(function() {
$('#filter').focusout(function() {
$('#options').hide();
});
})
jsfiddle with focusout: http://jsfiddle.net/yznhb8pc/1/
Use "blur": http://docs.jquery.com/Events/blur#fn
Like this:
$(selector).focusout(function () {
//Your Code
});
If the 'Cool Options' are hidden from the view before the field is focused then you would want to create this in JQuery instead of having it in the DOM so anyone using a screen reader wouldn't see unnecessary information. Why should they have to listen to it when we don't have to see it?
So you can setup variables like so:
var $coolOptions= $("<div id='options'></div>").text("Some cool options");
and then append (or prepend) on focus
$("input[name='input_name']").focus(function() {
$(this).append($coolOptions);
});
and then remove when the focus ends
$("input[name='input_name']").focusout(function() {
$('#options').remove();
});
Source: Stackoverflow.com