Cursor in search form by clicking on button

Viewed 76

I have an invisible search form that only appears when I click a button.

Is it somehow possible that when you click the button, the cursor is directly available in the search field? The "autofocus" attribute doesn't work here. Is there maybe a script solution?

Search form:

<div id="searchform">
    <form action="bla" method="post">
        ... <input type="text" name="item" id="search" placeholder="bla" autofocus /> ...
    </form>
</div>

Button:

<a id="button"></a>

Script:

<script>
    $(document).ready(function(){
        $('#searchform').hide();
        $("#button").click(function(){
            $("#searchform").slideToggle("fast");
        });
    });
</script>
1 Answers

To do what you require call focus() on the input as you make it visible:

$(document).ready(function() {
  $("#button").click(function() {
    $("#searchform").slideToggle("fast");
    $('#search').focus();
  });
});
#searchform { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="searchform">
  <form action="bla" method="post">
    <input type="text" name="item" id="search" placeholder="bla" autofocus /> ...
  </form>
</div>

<a id="button">Toggle form</a>

Note that I used CSS to hide the #searchForm element on load instead of JS, as this avoids the element being visible for a fraction of a second before the DOM is ready (aka a FOUC).

Related