Home:ALL Converter>Show searchbar and focus it after keypress

Show searchbar and focus it after keypress

Ask Time:2016-05-04T21:00:32         Author:Pascal Goldbach

Json Formatter

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>

Author:Pascal Goldbach,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/37028594/show-searchbar-and-focus-it-after-keypress
Pugazh :

Add input.focus(); to your function disparitionMenu(). Check below code.\n\n\r\n\r\nbuttonKeyAllowed = true;\r\n\r\nvar isVisible = false;\r\n\r\nfunction disparitionMenu()\r\n /* this function is used to show the searchbar */\r\n {\r\n var input = jQuery(\"#mod-search-searchword\");\r\n input[0].selectionStart = input[0].selectionEnd = input.val().length;\r\n jQuery(\"#menu-search\").css(\"display\", \"inline-block\");\r\n input.focus();\r\n }\r\n\r\n/*-- key events --*/\r\n\r\n\r\njQuery(document).keyup(function() {\r\n buttonKeyAllowed = true;\r\n});\r\n\r\njQuery(document).focus(function(e) {\r\n buttonKeyAllowed = true;\r\n});\r\n\r\njQuery(document).keypress(function(e) {\r\n\r\n if (e.repeat != undefined) {\r\n buttonKeyAllowed = !e.repeat;\r\n }\r\n if (!buttonKeyAllowed)\r\n return;\r\n buttonKeyAllowed = false;\r\n\r\n\r\n var code = (e.keyCode || e.which);\r\n\r\n if (code == 114) {\r\n if (!isVisible) {\r\n isVisible = true;\r\n e.preventDefault();\r\n }\r\n disparitionMenu();\r\n }\r\n});\r\n#menu-search {\r\n display: none;\r\n}\r\ninput {\r\n width: 100px;\r\n background-color: white;\r\n}\r\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\r\n\r\n\r\n<div id=\"megamenu\">\r\n <div id=\"menu-search\">\r\n <input type=\"text\" id=\"mod-search-searchword\" />\r\n </div>\r\n</div>",
2016-05-04T13:11:42
yy