EpicPineapple EpicPineapple - 10 days ago 6
HTML Question

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.

Answer

I have an update to my previous fiddle posted in my comment above. My previous fiddle still ran into the same problem after further testing of the double click.

After stepping through, the initial display value is coming back as "" not block. I'm not sure why its not taking your value you set in the <head></head> section but if you inline it like so:

<img id="p1" src="pic1.jpg" style="display: none;" />

it works correctly the first time with only one click of the button.

Here is my new updated fiddle demonstrating this.

I'm going to look more into why your styling in the <head></head> section but for now, here is a quick (and semi crude) fix.

Hope this helps and best of luck!