I was trying to make a snake game, I was just beginning to start animating my character by following code :
var head = document.getElementById("snakehead");
var pos = 0;
var direction = "right";
var val_type = "px";
var speed = 50;
var run = setInterval(move_right, speed);
function move_right() {
head.style.left = pos + val_type; //Concatination of value and "px" using "+"
pos += 10;
if (pos > 980) {
pos = 0;
}
}
body {
background-color: black;
}
#body-holder {
width: 1000px;
height: 700px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#header {
background-color: #1c1c1c;
font-family: impact;
font-size: 30px;
color: white;
width: 1000px;
height: 60px;
margin-bottom: 20px;
border-radius: 8px;
position: relative;
}
#title {
position: absolute;
left: 20px;
top: 50%;
transform: translate(0, -50%);
}
#score {
position: absolute;
right: 20px;
top: 50%;
transform: translate(0, -50%);
}
#playfield {
background-color: #1c1c1c;
width: 1000px;
height: 600px;
border: solid 10px white;
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
#snakehead {
width: 20px;
height: 20px;
background-color: red;
position: relative;
left: 0px;
top: 0px;
border-radius: 50px;
}
<body>
<div id="body-holder">
<div id="header">
<span id="title">Snake Game</span>
<span id="score">Score : 00</span>
</div>
<div id="playfield">
<div id="snakehead"></div>
<div id="body"></div>
</div>
</div>
</body>
and this runs well, but whenever I created any other function, it just stops running that setInterval command and the animation stops, like I added this simple function to just test :
function hi{
alert("Hello World!!");
}
Even adding this function or even an empty function freezes the whole javascript, then even if I call that hi()
function later on then still it doesn't work! Not even a normal alert function works at top of code then!!