Gabriel Luethje Gabriel Luethje - 1 year ago 109
CSS Question

Toggle focus to follow toggleClass

I'm doing a simple show/hide on a search form that uses jQuery's

and CSS to show and hide the form. That's easy enough, something like:


What I'd like to do but am having a hard time figuring out is to put focus on the search input when the form is shown and remove the focus from the search input when the form is hidden.

It's easy to add focus:

$('#site-search input[type="search"]').focus();

But I'm stuck at how to remove it when
is clicked again to hide the form.

Answer Source

OK I figured this one out, or at least I found a way to do what I need to do. I added a second class, search-closed, toggled both classes, then used each class to focus or blur the field, something like this:


    // toggle both classes
    $('#site-search').toggleClass('search-open search-closed');

    // set focus when form is visible, .search-open
    // use setTimeout to make sure the cursor actually gets in there
    // don't know why, but it works
    setTimeout (function(){
        $(' .site-search__input').focus();
    }, 20);

    // blur when the form is not visible, .search-closed
    $(' .site-search__input').blur();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download