Reputation: 1497
I have a search form that appears when an icon is clicked. But the focus remains on the icon, and the user has to click again inside the search box in order to be able to type. How can I shift the focus to the input box after the form appears?
My code looks like this.
ICON:
<span class="search-item">
<button aria-expanded="false" class="search-toggle">
<svg class="icon icon-search" aria-hidden="true" role="img" focusable="false">
<use href="#icon-search" xlink:href="#icon-search"></use>
</svg>
<svg class="icon icon-close" aria-hidden="true" role="img" focusable="false">
<use href="#icon-close" xlink:href="#icon-close"></use>
</svg>
</button>
</span>
FORM that opens when icon is clicked:
<form role="search" method="get" class="search-form" itemprop="potentialAction" itemscope="itemscope" itemtype="http://schema.org/SearchAction" action="https://www.example.com/">
<label class="label-search">
<span class="screen-reader-text">SEARCH</span>
<input type="search" class="search-field" itemprop="query-input" placeholder="Search..." value="" name="s" title="Search">
</label>
<button type="submit" class="search-submit">
<svg class="icon icon-search" aria-hidden="true" role="img" focusable="false">
<use href="#icon-search" xlink:href="#icon-search"></use>
</svg>
<span class="screen-reader-text">SEARCH</span>
</button>
</form>
SEARCH FUNCTION from functions.php:
public static function primary_nav_search( $args ) {
if ( 'primary' !== $args['theme_location'] ) {
return $args;
}
if ( '' === get_theme_mod('manta_nav_search', manta_get_theme_defaults( 'manta_nav_search' ) ) ) {
return $args;
}
$search_toggle = sprintf( '<button aria-expanded="false"%1$s>%2$s%3$s</button>', manta_get_attr( 'search-toggle' ), manta_get_icon( array( 'icon' => 'search' ) ), manta_get_icon( array( 'icon' => 'close' ) ) );
$search_item = sprintf( '<span%1$s>%2$s</span>', manta_get_attr( 'search-item' ), $search_toggle );
$args['items_wrap'] = get_search_form( false ) . $args['items_wrap'] . $search_item;
return $args;
}
Can this be done, is it possible? Thank you.
Upvotes: 0
Views: 2960
Reputation: 56
Edit : woops, I see no js here, but you can still use the HTML <script>
tag
You should consider using the javascript element.blur()
to remove the focus and element.focus()
to set the focus on another element.
More info there :
Blur() - https://www.w3schools.com/jsref/met_html_blur.asp
Focus() - https://www.w3schools.com/jsref/met_html_focus.asp
In your HTML file, try the following :
<script>
const iconSearch = document.querySelector('.search-toggle');
const searchField = document.querySelector('.search-field');
iconSearch.addEventListener("click", function () {
searchField.focus();
});
</script>
Upvotes: 2