0
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Handler</title>
</head>

<style>
    P{
        opacity: 1;
        transition: all .5s;
    }
</style>

<body>
    <div class="container">
        <h1>Welcome</h1>
        <p id="para">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
        <button id="button">Toggle Hide</button>
    </div>

    <script>
        let para = document.getElementById("para");
        let button = document.getElementById("button");

        button.addEventListener("click", function hide(){
            para.style.opacity == "0" ? para.style.opacity = "1" : para.style.opacity = "0";
        });
    </script>
</body>
</html>

The above code is a simple html code with a Heading, "Welcome", a paragraph and a button. Whenever I click the button I want to toggle the opacity of the paragraph. Inside the "script" tag I am using this code to achieve this:

button.addEventListener("click", function hide(){
   para.style.opacity == "0" ? para.style.opacity = "1" : para.style.opacity = "0";
});

Now it works completely fine. However when I write it this way it doesn't work on first click. I have to click twice to make this work.

button.addEventListener("click", function hide(){
    para.style.opacity == "1" ? para.style.opacity = "0" : para.style.opacity = "1";
});

Any idea why this happens?

  • Because on the first click there is no inline style on the element. You should use `window.getComputedStyle` to read the actual opacity computed for your button. – Terry Jul 15 '23 at 09:37
  • 1
    @DoanThai — No. Really not. It's completely unnecessary here as the element exists before the script runs. Even if that wan't the case, IE 8 is dead so we don't need to use `onXYZ` attributes with all their drawbacks today. Also *load* and *DOM ready* are not the same thing; *load* runs much later. – Quentin Jul 15 '23 at 09:46

0 Answers0