Search code examples
javascripthtmlopacity

how to change the opaqueness of a colored box by click a button?


I have a homework to make a box fade which means to click a button to change the opacity of a colored box. but I couldn't make it work. below are some coding. what is wrong? thanks a lot.

<button id="button3">Fade</button>

document.getElementById("button3").addEventListener("click", function(){
  document.getElementById("box").style.Opacity = "0.5";
});

Solution

  • The problems

    1. you are trying to access an element with id of box

    2. As heretic monkey said, javascript is case-sensitive, meaning Opacity should be opacity

    Fixing the above

    document.getElementById("button3").addEventListener("click", function(){
      document.getElementById("button3").style.opacity = "0.5";
    });
    <button id="button3">Fade</button>

    More reading

    Note: JavaScript is case sensitive — myVariable is a different variable to myvariable. If you are getting problems in your code, check the casing!