<!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?