This should be simple, but I don't understand why it isn't working as expected. I have a search bar that, by default, has a class of "search-bar--hidden," which applies a property of "display: none." A class of "search-bar--visible" applies "display: flex."
I have a function to toggle those classes.
In my HTML, I have:
<div class="site-head__icn-search" onclick="toggleSearch()">
<i class="fas fa-search"></i>
</div>
And in my JavaScript I have:
function toggleSearch() {
var searchBar = document.getElementById("search-bar");
var searchInput = document.getElementById("search-bar-input");
if (searchBar.classList.contains("search-bar--hidden")) {
searchBar.classList.remove("search-bar--hidden");
searchBar.classList.add("search-bar--visible");
searchInput.focus();
} else {
searchBar.classList.remove("search-bar--visible");
searchBar.classList.add("search-bar--hidden");
searchInput.blur();
}
}
When I click on the search icon, the search box does appear as expected. And when I click it again, it disappears....but when I release that second click, it appears again. It's almost like the browser is detecting an additional click somehow.
You can see all of this in action at http://www.christmaspast.media
Can anyone help me understand what's going on?
try like this
function toggleSearch(e) {
if (!e.target.classList.contains('site-head__icn-search') &&
!e.target.closest('.site-head__icn-search').classList.contains('site-
head__icn-search'))
return false;
var searchBar = document.getElementById("search-bar");
var searchInput = document.getElementById("search-bar-input");
if (searchBar.classList.contains("search-bar--hidden")) {
searchBar.classList.remove("search-bar--hidden");
searchBar.classList.add("search-bar--visible");
searchInput.focus();
} else {
searchBar.classList.remove("search-bar--visible");
searchBar.classList.add("search-bar--hidden");
searchInput.blur();
}
}
<div class="site-head__icn-search" onclick="toggleSearch(event)">
<i class="fas fa-search"></i>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.