Milind Pandharkame Milind Pandharkame - 4 months ago 8
CSS Question

Javascript - When a button is clicked the CSS property toggle after second click

I am working on a simple Play and Pause button code with Javascript. The script is toggling the CSS property; however, after a delay. At the moment, the toggle happens on second click. Not sure what the issue is.



$(document).click(function () {
$("#startClock").click(function () {
$("#startClock").css("display", "none");
$("#stopClock").css("display", "block");
});
$("#stopClock").click(function () {
$("#stopClock").css("display", "none");
$("#startClock").css("display", "block");
});
});

#stopClock {
display: none;
}

#startClock {
display: block;
}

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js?ver=4.1'></script>
<button id=startClock >Start</button>
<button id=stopClock >Pause</button> <br/>




Answer

Instead of $(document).click go for $(document).ready

$(document).ready(function () {
	    $("#startClock").click(function () {
	        $("#startClock").css("display", "none");
	        $("#stopClock").css("display", "block");
	    });
	    $("#stopClock").click(function () {
	        $("#stopClock").css("display", "none");
	        $("#startClock").css("display", "block");
	    });
	});
#stopClock {
  display: none; 
}

#startClock {
  display: block;   
}
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js?ver=4.1'></script>
<button id=startClock >Start</button>
<button id=stopClock >Pause</button> <br/>

It was happening because on first click which was getting listen by document; the click event handler were getting attached to your button. Hence needed 2 clicks for the CSS animation.