Search code examples
javascripthtmlcssbuttonopacity

How would i get a button to change a objects opacity with html, js & css


I wanted to make a button to hide the weather section of my website landing page but i do not know how to make it! Image

I currently use a "selector" so i can select either 0 or 1 which you can see in the bottom right, and it works nicely but i would perfer a button. Here is my current code that i use:

</div>
  <div class="wopacity">
   <select onchange="myFunction(this);" size="2">
   <option>0
   <option selected="selected">1
   </select>

   <script>
    function myFunction(x) {
     // Return the text of the selected option
     var opacity = x.options[x.selectedIndex].text;
     var el = document.getElementById("p1");
     if (el.style.opacity !== undefined) {
       el.style.opacity = opacity;
     } else {
       alert("Your browser doesn't support this example!");
     }
    }
   </script>
  </div>

Solution

  • If you want to use a button, you could add a data-* attribute to the button. It would look something like

    <html>
    <head>
    <script>
        function myFunction(button) {
           // get data-opacity
           let opacity = button.dataset.opacity;
           const el = document.getElementById("p1");
           el.style.opacity = opacity;
    
           /* shorthand for
                if (opacity === "1") {
                  button.dataset.opacity === "0";
                else {
                  button.dataset.opacity === "1";
                }
           */
           button.dataset.opacity = opacity === "1" ? "0" : "1";
         }
    </script>
    </head>
    <body>
    <div id="p1">Opacity test</div>
    <button data-opacity="0" onclick="myFunction(this)">Change opacity</button>
    </body>
    </html>

    Is this actually what you want or did I get the question wrong?