Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/Javascript - Button takes two clicks to execute click event

Testing out a simple toggle display, however, it takes two clicks to toggle the display the first time. Afterwards it does it in one.

<html>
<head>
<style>
#carousel{border:2px solid blue;
width:1280px;
height:720px;}

#p2{visibility:hidden;}

#p1{display:block;}

#btn{position:absolute;
    top:2000px;}
</style>

<script src="mainScript.js"></script>
</head>

<body>

<div id="carousel">
    <img id="p1" src="pic1.jpg">
    <img id="p2" src="pic2.jpg">
</div>

<button type="button" id="button" onclick="clickEvent()">Click</button>

</body>
</html>

And here is my javascript:

function clickEvent(){
var p = document.getElementById("p1");
if(p.style.display == "block")
    p.style.display = "none";
else
    p.style.display = "block";
}

It should be noted I am using no jQuery, as all other questions I found about this were jQuery related.

like image 372
starscape Avatar asked Oct 14 '25 10:10

starscape


1 Answers

function clickEvent(){
var p = document.getElementById("p1");
if(p.style.display == "none")
    p.style.display = "block";
else
    p.style.display = "none";
}

you can also simplify things a bit:

p.style.display = p.style.display == "none" ? "block" : "none";
like image 62
ic3b3rg Avatar answered Oct 16 '25 22:10

ic3b3rg