Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the display of an element via Javascript?

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!

like image 933
Chris Lallo Avatar asked Oct 19 '25 02:10

Chris Lallo


1 Answers

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.

like image 59
ashish singh Avatar answered Oct 21 '25 17:10

ashish singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!