简体   繁体   中英

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:

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

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

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

Like this:

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

使用“模糊”: http : //docs.jquery.com/Events/blur#fn

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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM