I'm struggling with a simple movement engine I created. When the Up key is pressed, a function moves a small div
up, and when the Down key is pressed, it does the opposite. I suspect the issue lies with the +=
in the Down()
function, as changing it to -=
resolves the problem. However, I can't seem to identify what might be conflicting with the function.
My problematic area is marked by a comment at the bottom.
var interval = '';
var key = false;
var interval1 = '';
var key1 = false;
$(document).keydown(function(e) {
if(e.which === 38) {
if(key === false){
interval = setInterval(function(){Up()},20)
key = true;
}
}
if(e.which === 40) {
if(key1 === false){
interval1 = setInterval(function(){Down()},20)
key1 = true;
}
}
});
$(document).keyup(function(e) {
if(e.which === 38) {
clearInterval(interval)
key = false;
}
if(e.which === 40) {
clearInterval(interval1)
key1 = false;
}
});
document.getElementById('Jumper').style.top = '46%';
var Top = parseInt(document.getElementById('Jumper').style.top);
var Topp = parseInt(document.getElementById('Jumper').style.top);
function Up(){
if(Top > 0){
Top = parseInt(document.getElementById('Jumper').style.top);
Top -= 0.2;
document.getElementById('Jumper').style.top = Top+'%';
}
}
function Down(){
if(Topp > 0){
Topp = parseInt(document.getElementById('Jumper').style.top);
Topp += 0.2; //<--PROBLEM
document.getElementById('Jumper').style.top = Topp+'%';
}
}
#Jumper{
position: absolute;
top: 46%;
left: 48%;
height: 8%;
width: 4%;
background-color: red;
opacity: 1;
}
<div id='Jumper'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
I would appreciate any insights on how to resolve this issue.
Check out this fiddle: https://jsfiddle.net/Tobsta/2gnoq5hx/