EpicPineapple EpicPineapple - 4 months ago 40
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.

#carousel{border:2px solid blue;




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


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

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


And here is my javascript:

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

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


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!