In my code i’m trying to compare the height with the position of an element, to ensure that the element doesn’t leave the game’s div.
First I get the position of my element, snake. and if the cursor is too close then i move it. Then at the end I do a check that it is at least 20 pixels away from the top and bottom. For some reason everything is working except the when it reaches the bottom of the screen (which is the else if statement in the end block of code)
var posL = $("#snake").position().left;
var posT = $("#snake").position().top;
if((e.pageX-200 < posL) && (posL < e.pageX-50)){
if(posL > 20){
posL = posL - 5;
}else{
posT = posT + 5;
}
…
if(posT < 20){
posT = 20;
}else if(posT > parseInt($("#game").height)){
posT = parseInt($("#game").height) - 20;
}
You forgot the
()after.height…twice! 😉