+ 4

onclick is clicked when generated

I'm applying the onclick to the entire HTML page in order to make a function happen when clicked anywhere. But when I apply the property it clicks on it once automatically. Can anyone help me? :/ https://code.sololearn.com/W8Eo92JgBmLc/#html

17th Mar 2019, 3:03 PM
Matteo Consolaro
Matteo Consolaro - avatar
2 Réponses
+ 9
//You can try this: //in js section var times = 1,clicked=false; //clicked for holding state function toHtml(){ clicked = true; document.getElementById("entirePage").onclick = function(){ clickAnywhere() }; var bu = "removeMe"; removeButtons(bu); } function removeButtons(containerID){ //rimuove childNodes var i = document.getElementById(containerID); while (i.hasChildNodes()) { i.removeChild(i.lastChild); } } function clickAnywhere(){ if(!clicked){ console.log("you just clicked anywhere " + times + " times! Hehe"); times++; } else{ clicked=false; } }
17th Mar 2019, 3:43 PM
VEDANG
VEDANG - avatar
+ 2
Thanks so much for the answer, I've been on this for a couple of hours. If I got it right, when the page click happens (after mouse release) the onclick property is already set. So both commands are executed together. So i thought of a little timeout "hack" that apparently works too. First function becomes: function toHtml(){ var bu = "removeMe"; removeButtons(bu); setTimeout(function(){ document.getElementById("entirePage").onclick = clickAnywhere;}, 0); }
17th Mar 2019, 4:09 PM
Matteo Consolaro
Matteo Consolaro - avatar