Forms, Javascript, jQuery | Type: PHPToggling search form and focus search field

Nothing tricky about toggling a search form, but making the search field focus upon showing was hard to find. For an example, see the search button on the main navigation above (desktop only).

jQuery

jQuery(document).ready(function($) {
   $(".search_icon").click(function() {
       $(".evosearchform").slideToggle();
       $("input:text:visible:first").focus(); //this is the part that creates focus
   });
   $(document).keydown(function(e) {
       if (e.keyCode == 27) {
       $(".evosearchform").hide();
       }
   });
});


HTML

The toggle button (note .evosearch_icon displays a search icon as a bkgrd image):

<li class="search"><a class="search_icon"><span class="evosearch_icon"></span></a></li>


The search form (toggles open and closed)
You’ll note ‘autofocus’ on the search field, but it actually does not create focus when the search form is toggled.

<div style="display:none;" class="evosearchform">
<form method="get" id="search" action="<?php echo esc_url(home_url()); ?>">
    <?php $req=''; ?>
    <input type="text" autofocus name="s" id="s" placeholder="Search this site" value="<?php echo get_search_query(); ?>" />
    <button type="submit">Search</button>
</form>
</div>

Reference Links