Hunor Német Hunor Német - 1 month ago 7
HTML Question

How to make a javascript load after other page elements are loaded?

So I made this rock-paper-scissors game in HTML. when the page loads, it asks the user for their input through a pop-up. The problem is the popup loads before any of my divs and I want all my html elements to be visible before the popup script starts.

Here is my code:

<body>
<div class="user">
<div class="container">You choose:</div>
<div id="userInput"></div>
</div>
<div class="computer">
<div class="container">Computer chooses:</div>
<div id="computerInput"></div>
</div>
<div class="results">
<div class="container">Results:</div>
<div id="resultsOutput"></div>
</div>

<script type="text/javascript">
var userInput = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
var userChoice = userInput
} else {
userChoice = "Invalid entry, sorry. "
}

if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);

function compare(choice1, choice2) {
if (userInput === "rock" || userInput === "paper" || userInput === "scissors") {
if (choice1 === choice2) {
return "The result is a tie!";
} else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
} else {
return "paper wins"
}
} else if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
} else {
return "scissors wins";
}
} else if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";
} else {
return "scissors wins"
}
}
} else {
return "Results not calculated."
}
}
document.getElementById("userInput").innerHTML = userChoice;
document.getElementById("computerInput").innerHTML = computerChoice
compare(userChoice, computerChoice);
document.getElementById("resultsOutput").innerHTML = compare(userChoice, computerChoice)

</script>
</body>

Answer

Your javascript is executed before the rest of the page has been loaded

You are trying to use window.onload, but you are doing it wrong. window.onload should be a function, like this:

window.onload = function(){
    //your code here
}

But this only works if you only have ONE function you want to start on page load. In general it's better to use the window.addEventListener method, since you can use multiple of those and all will be executed.

If you would use another window.onload = function(){}, it would override the first one.

That's why I recomment using:

window.addEventListener('load',function(){
    //your code here
})