jQuery lose focus event

jQuery lose focus event

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:

some cool options

And what I’d like to do is something like this:
$(‘#filter’).focus_lost(function() {
$(‘#options’).hide();
});

Solutions/Answers:

Solution 1:

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

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

Solution 2:

Like this:

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

Solution 3:

Use “blur”:
http://docs.jquery.com/Events/blur#fn

Solution 4:

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:

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

Related:  SyntaxError: Unexpected token function - Async Await Nodejs