Pascal Goldbach Pascal Goldbach - 6 months ago 22
Javascript Question

Show searchbar and focus it after keypress

I want to show a searchbar when the user presses the "R" key, the searchbar should also be focused after the key press, here's the fiddle:



buttonKeyAllowed = true;

function disparitionMenu()
/* this function is used to show the searchbar */
{
var input = jQuery("#mod-search-searchword");
input[0].selectionStart = input[0].selectionEnd = input.val().length;
jQuery("#menu-search").css("display", "inline-block");
}

/*-- key events --*/


jQuery(document).keyup(function() {
buttonKeyAllowed = true;
});


jQuery(document).focus(function(e) {
buttonKeyAllowed = true;
});


jQuery(document).keypress(function(e) {

if (e.repeat != undefined) {
buttonKeyAllowed = !e.repeat;
}
if (!buttonKeyAllowed)
return;
buttonKeyAllowed = false;


var code = (e.keyCode || e.which);

if(code == 114) {
disparitionMenu();
}
});

#menu-search
{
display: none;
}

input{
width: 100px;
background-color: white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div id="megamenu">
<div id="menu-search">
<input type="text" id="mod-search-searchword" />
</div>
</div>





This code works nice, but there's one problem:

When the user presses the "R" key a little bit too long, 'r' is written in the searchbar, and I want to avoid it.

What's the cleanest way to correct this problem? I don't want to add a
while(/* is R key down*/){}
loop before the function
disparitionMenu()


Thank you for your help.

Answer

Add input.focus(); to your function disparitionMenu(). Check below code.

buttonKeyAllowed = true;

var isVisible = false;

function disparitionMenu()
  /* this function is used to show the searchbar */
  {
    var input = jQuery("#mod-search-searchword");
    input[0].selectionStart = input[0].selectionEnd = input.val().length;
    jQuery("#menu-search").css("display", "inline-block");
    input.focus();
  }

/*-- key events --*/


jQuery(document).keyup(function() {
  buttonKeyAllowed = true;
});

jQuery(document).focus(function(e) {
  buttonKeyAllowed = true;
});

jQuery(document).keypress(function(e) {

  if (e.repeat != undefined) {
    buttonKeyAllowed = !e.repeat;
  }
  if (!buttonKeyAllowed)
    return;
  buttonKeyAllowed = false;


  var code = (e.keyCode || e.which);

  if (code == 114) {
    if (!isVisible) {
      isVisible = true;
      e.preventDefault();
    }
    disparitionMenu();
  }
});
#menu-search {
  display: none;
}
input {
  width: 100px;
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


<div id="megamenu">
  <div id="menu-search">
    <input type="text" id="mod-search-searchword" />
  </div>
</div>

Comments