Reputation: 393
I'm trying to learn some programming with jQuery. I have a div that has 800 x 800 pixel dimensions. I have another 16 x 16 pixel div that I want to move within the bigger one using arrow keys. Problem is I can't get it to work properly, can someone please tell me what I'm doing wrong.
Moving left works, it stops the 16x16 div if css attribute "left" is under 0px:
$(this).keydown(function(e) {
if (e.which == '37' && ($('#p1').css('left') > "0px")) {
$('#p1').css('left', '-=16px')
}
});
Moving right doesn't work, it stops the 16x16 div at 80px from the left, no matter what value above 80px I try:
$(this).keydown(function(e) {
if (e.which == '39' && ($('#p1').css('left') < '800px')) {
$('#p1').css('left', '+=16px')
}
});
Also moving up and down using similar method doesn't work, movement is restricted incorrectly. Moving in all direction works fine without &&
arguments.
Upvotes: 1
Views: 1046
Reputation: 5781
Taking the answer from jermel as well I would also clean up the code a bit to something like this
$(document).ready(function() {
$(document).keydown(function(e){
var left = parseInt($('#p1').css('left'),10);
if (e.keyCode === 37 && (left > 0)) {
$('#p1').css('left', left-16);
}
if (e.keyCode === 39 && (left < 800)) {
$('#p1').css('left',left+16);
}
});
});
Upvotes: 0
Reputation: 2336
Your problem is:
css('left') < '800px')
You are comparing strings instead of numbers;
Try:
var left = parseInt($('#p1').css('left'),10);
if (e.which == '39' && (left < 800)) {...
Upvotes: 2