javascriptcssonclick

why do my onClick functions take two clicks


I've noticed from a few different projects of mine that whenever I click something I add an onClick function to, it always takes two clicks to get them going when a page is freshly loaded. The general structure I use for them is:

function PageChange(){

    var welc_p = document.getElementById("welcome");/**gathers page DIVs**/
    var page01 = document.getElementById("page01");
    var page02 = document.getElementById("page02");

    var start = document.getElementById("start_btn");/**gathers buttons**/
    var p1_back = document.getElementById("p1_back");
    var p1_next = document.getElementById("p1_back");

    var p2_back = document.getElementById("p2_back");
    var p2_next = document.getElementById("p2_back");

    start.onclick=function(){
        page01.style.display="block";
        welc_p.style.display="none";
        window.location="#page01";
        };

    }/**function**/

then the way I call it in the html is

<div class="some_class" id="start_btn" onClick="PageChange()">!!!LETS GET STARTED!!!</div>

Here's a fiddle of it as well. https://jsfiddle.net/Optiq/42e3juta/

this is generally how I structure it each time I want to create this functionality. I've seen tons of other posts on here about their items taking 2 clicks to activate but none of them were doing anything near what I was trying to accomplish and it seemed their problem was within their coding. Does anybody know why this is happening?


Solution

  • This is because you are attatching a event handler to your button on click of your button.
    This means that one click of the button activates the event handler, not the code within start.onclick=function() {
    Then, the second click works becasue the event handler has been activated, and now the code will run.

    Try moving your code out of the function, then it will work with just one click