Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Prevent focus loss of input when clicking on specific element

Tags:

jquery

I have an input that contains a custom drop down menu. When you click on a menu item it should set the value of the input to the text of the item. I also want the menu to hide when the input loses focus. This has created a problem, where clicking a menu item makes the input lose focus and hide the menu before the click event for the menu item can be run. How do I fix this?

$(document).on('click', '#inputMenu li', function (e) {
    $('#input').val($(this).text());
    $('#inputMenu').removeClass('active');
    e.preventDefault();
    return false
});
  
$('#input').on('focusout',function(e) {
    $('#inputMenu').removeClass('active');
});
 
$('#input').on('input',function(e) {
    $('#inputMenu').addClass('active');
});
#inputMenu {
  display: none;
}

#inputMenu.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input" type="text" placeholder="type something">
<ul id="inputMenu">
  <li>Click me to set text 1</li>
  <li>Click me to set text 2</li>
  <li>Click me to set text 3</li>
  <li>Click me to set text 4</li>
</ul>
like image 525
Settings Menu Hard to Find Avatar asked Dec 09 '18 12:12

Settings Menu Hard to Find


1 Answers

This problem is caused by the order of events. There is a trick you can use, replace click event with mousedown which is fired before focusout.

$(document).on('mousedown', '#inputMenu li', function (e) {
    $('#input').val($(this).text());
    $('#inputMenu').removeClass('active');
    e.preventDefault();
    return false
});
  
$('#input').on('focusout',function(e) {
    $('#inputMenu').removeClass('active');
});
 
$('#input').on('input',function(e) {
    $('#inputMenu').addClass('active');
});
#inputMenu {
  display: none;
}

#inputMenu.active {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input" type="text" placeholder="type something">
<ul id="inputMenu">
  <li>Click me to set text 1</li>
  <li>Click me to set text 2</li>
  <li>Click me to set text 3</li>
  <li>Click me to set text 4</li>
</ul>

Credits:

This answer was originally posted here

like image 188
Ahmad Maleki Avatar answered Oct 13 '22 13:10

Ahmad Maleki