How to improve "on keyup" speed?

Viewed 2567

Here is my code:

$('#MyInput').on('keyup', function (e) {
      if ($(this).val().length == 1) {
          ajaxSearch($(this).val());
     }
});

I want to run a function when the input has only one character.

The problem is that if the user type a word really fast, the 'keyup' event seems to be called starting from the second character, which means it will not call ajaxSearch() method.

Is there any way to improve the 'keyup' event speed to call the function when it has only 1 character?

2 Answers

When user types too fast, he/she may have not released the previous key yet, so keyup technically hasn't happened yet.

Try keypress instead of keyup

$('#MyInput').on('keypress', function (e) {
      if ($(this).val().length == 1) {
          ajaxSearch($(this).val());
     }
});

Edit

On keypress input's value property has not be been updated yet, so catch keyup as well in case user only inputs a single character.

$('#MyInput').on('keypress', function (e) {
      if ($(this).val().length == 1) {
          ajaxSearch($(this).val());
     }
});

$('#MyInput').on('keyup keypress', function(e) {
  if ($(this).val().length == 1) {
    ajaxSearch($(this).val(),e);
  }
});

function ajaxSearch(value,e) {
  console.log(value, e.type)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="MyInput">

Try keypress instead of keyup

$('#MyInput').on('keypress', function (e) {
      if ($(this).val().length == 1) {
          ajaxSearch($(this).val());
     }
});
Related