0

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>

2 Answers2

0

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?

Terry
  • 66
  • 2
  • Thats wonderful thanks! Ill just edit the style of the button in css now, thanks so much! How would i change the button to be an image or a circle shape? – MountainTiger144 Aug 22 '20 at 11:34
  • For an image you could use the tag, with the data-opacity and onclick attributes. If you want a circle shape, you could leave the button there, but style it accordingly. Add a border-radius to the button (border-radius: 50% should be enough) – Terry Aug 22 '20 at 16:10
0

You can create a button and get it using javascript and then show and hide the weather div using CSS property display: none or display: block. The following code will resolve will solve your problem.

<html>
 <head>
  <script>
  function myFunction(button) {
   const ele = document.getElementById("weatherElem");
   el.style.display = el.style.display === "none" ? "block" : "none";
 }
 </script>
  <div id="weatherElem">Weather Element</div>
  <button id="button" onclick="myFunction(this)">Toogl weather</button>
 </body>
</html>
Mehdi Rajani
  • 161
  • 6