简体   繁体   中英

execute jquery command unless user clicks on a div

I have a user search bar that creates a div containing the relevant users and it disappears when you focus out. However I don't want to focus out if I click on the user list div. Is this possible to achieve?

application.js:

$(function() {
   $("#user_header_search_form input").focusout(function() {
      $('#header_user_list').html('');
   });
});

$('#header_user_list').html(''); I don't want to run this link if the user clicks '#header_user_list'

An alternativa approach may be:

 $(document).click(function(event){

    var clicked = $(event.target);

    //if the clicked element is not son of the input or the list, clear the list.
    if(clicked.closest("#user_header_search_form input,#header_user_list").size() == 0)
    $('#header_user_list').html('');

 });

Another option is setting a delay before clearing the list. This will work if the user must pick only one item from the list:

 $("#user_header_search_form input").focusout(function() {
     setTimeout(function(){
        $('#header_user_list').html('');
     },50);
 });

Hope it helps!

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