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.

jQuery

jQuery(document).ready(function($) {
   $(".search_icon").click(function() {
       $(".evosearchform").slideToggle();
       $("input:text:visible:first").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)

<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

We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept