Search code examples
htmljqueryformsbuttonsubmit

Style changes on button "onclick" not working


I would like for when the button is clicked for the svg on the button to go green while a form appears. At the moment I have:

<button onclick="onclick="main-search.style.display = 'block'; search-icon.style.stroke = '#00ac46';" class="search-btn" type="submit">
        <svg xmlns="http://www.w3.org/2000/svg" width="22" height="19" viewBox="0 0 22 19" fill="none">
            <circle cx="8.38555" cy="8.38555" r="6.88555" stroke="#D8D8D8" stroke-width="3"/>
            <line x1="13.0553" y1="11.5686" x2="20.9848" y2="17.7638" stroke="#D8D8D8" stroke-width="3"/>
        </svg>
</button>
<form class="search" action="/search">
    <input type="text" placeholder="Search" name="q" value="{{ search.terms | escape }}"  />
</form>
.main-search { 
     display: none; 
}

I've also tried onclick="showBar()"

and

let slideSearch = document.querySelector("main-search");
let greenButton = document.querySelector("search-icon");
    function showBar() { 
        slideSearch.style.display = "block";
        greenButton.style.stroke = "#00ac46";
    }

If anyone knows what's wrong with the code or can provide an alternative code that works, that would be much appreciated-thanks!


Solution

  • a) onclick="onclick=".... needs to be simply onclick="showBar();"

    b) Your code doesn't have those 2 classes through which you want the changes to be made. (main-search and search-btn)

    c) querySelector need . or # included while providing the selector class or id. You are missing that and hence, your code is not working.

    d) The button has no stroke style property, instead, it has background and border-color properties, which you can use.

    Working snippet:

    let slideSearch = document.querySelector(".main-search");
    let greenButton = document.querySelector(".search-btn");
    
    function showBar() {
      slideSearch.style.display = "block";
      greenButton.style.background = "#00ac46";
      greenButton.style.borderColor = "#00ac46";
    }
    .main-search {
      display: none;
    }
    <button onclick="showBar();" class="search-btn" type="submit">
    <svg xmlns="http://www.w3.org/2000/svg " width="22 " height="19" viewBox="0 0 22 19" fill="none"><circle cx="8.38555" cy="8.38555" r="6.88555" stroke="#D8D8D8" stroke-width="3"/>
    <line x1="13.0553" y1="11.5686" x2="20.9848" y2="17.7638" stroke="#D8D8D8" stroke-width="3"/>
    </svg>
    </button>
    <br/><br/>
    <form class="main-search" action="/search">
      <input type="text" placeholder="Search" name="q" value="1" />
    </form>