jQuery lose focus event

JavascriptJqueryFocusJquery Events

Javascript Problem Overview


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();
});

Javascript Solutions


Solution 1 - Javascript

Use blur event to call your function when element loses focus :

$('#filter').blur(function() {
  $('#options').hide();
});

Solution 2 - Javascript

Like this:

$(selector).focusout(function () {
    //Your Code
});

Solution 3 - Javascript

Solution 4 - Javascript

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/

Solution 5 - Javascript

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();
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxijoView Question on Stackoverflow
Solution 1 - JavascriptCanavarView Answer on Stackoverflow
Solution 2 - JavascriptSoftwareARMView Answer on Stackoverflow
Solution 3 - JavascriptNVRAMView Answer on Stackoverflow
Solution 4 - JavascriptRazan PaulView Answer on Stackoverflow
Solution 5 - JavascriptSproseView Answer on Stackoverflow