I have a search bar with a toggle button directly above it. The toggle works just fine, but my issue is that I want the form to start disabled. My toggle button utilizes the display property, but when I set that property through CSS as disabled, the toggle no longer works. I also found that there isn't an attribute for that in HTML, so I'm pretty lost. Here's my Javascript spun into my HTML:
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
if (searchbar.style.display == "none") {
searchbar.style.display = "";
} else {
searchbar.style.display = "none";
}
}
.search-button form {
display: none;
padding-top: 10px;
}
<div class="search-button">
<p onclick="ToggleSearchBar()">Search</p>
<form id="SearchBar">
<input type="text" placeholder="Your query here">
</form>
</div>
So to reiterate, I just need the form element to start with a display of none, while still allowing for my Javascript to function as intended. Any help would be appreciated. Thanks!
the problem here is element.style.display
accesses inline style property to get the property applied to the element you can use getComputedStyle
function
function ToggleSearchBar() {
var searchbar = document.getElementById("SearchBar");
var display = getComputedStyle(searchbar).display;
if (display == "none") {
searchbar.style.display = "block";
} else {
searchbar.style.display = "none";
}
}
.search-button form {
display: none;
padding-top: 10px;
}
<div class = "search-button">
<p onclick = "ToggleSearchBar()">Search</p>
<form id = "SearchBar">
<input type = "text" placeholder = "Your query here">
</form>
</div>
and you have to use display block
instead of empty string as you have a css declaration of none
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With