<meta charset="UTF-8">
<title>Reaction game</title>
<style>
#container {
background: lightgreen;
width: 900px;
height: 900px;
margin: auto;
display: flex;
position: relative;
}
.div {
background: red;
width: 60px;
height: 60px;
}
</style>
<div id="container">
</div>
<script>
let container = document.getElementById("container");
let speedX = 60;
function moveThis(element) {
let currentLeft = parseInt(this.style.left) || 0;
this.style.left = (leftOrRight() === 0 ? currentLeft + speedX : currentLeft - speedX) + "px";
speedX += 2;
}
function generateDiv() {
let newDiv = document.createElement("div");
newDiv.classList.add("div");
container.appendChild(newDiv);
let style = newDiv.style;
style.position = "absolute";
function leftOrRight() {
let value = Math.random();
if(value < 0.5) {
return 0
}else {
return 1;
}
}
style.left = leftOrRight() === 0 ? 0 : 840 + "px";
style.top = Math.floor(Math.random() * 840)+ "px";
moveThis.bind(newDiv)();
console.log(leftOrRight());
};
setInterval(generateDiv, 1000)
</script>
Uncaught ReferenceError: leftOrRight is not defined
Can someone who is good at JavaScript help me to move the newDiv
:to left if its position is on right or
:to right if its position is on left?
Please help me with this code!
ChatGPT unfortunately didn’t help me. ðŸ˜
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
it asks me for more information
3
Answers
You defined the
leftOrRight()
function inside thegenerateDiv()
function. So calling it inside themoveThis()
will definitely throw an error.You should define the
leftOrRight()
function outside body of thegenerateDiv()
function.This way:
Goodluck!
You defined leftOrRight() inside generateDiv() scope. But called it inside moveThis() (out side of generateDive function scope). It is out of scope.
Read more about function/variable scope
If I can see correctly, you’ve tried to reference
leftOrRight
from themoveThis
function. Meanwhile,leftOrRight
is defined in another function calledgenerateDiv
. This means that the reference calledleftOrRight
is only accessible from the inside ofgenerateDiv
function. To solve this, just move theleftOrRight
definition out, and place it before the definition ofmoveThis
.I hope that I’ve understood your question correctly, and this will solve it!