1

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.

fnx
  • 369
  • 1
  • 5
  • 16
  • This might be a duplicate: http://stackoverflow.com/questions/8628368/how-do-i-implement-collision-detection-between-a-set-of-div-elements – Anderson Green Dec 29 '12 at 05:22

2 Answers2

2

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)) {...
jermel
  • 2,326
  • 21
  • 19
0

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);
        }



    });


});
bretterer
  • 5,693
  • 5
  • 32
  • 53
  • Thanks for this! Didn't realize I wasn't playing with numbers. Now my code works like a charm. – fnx Jan 12 '12 at 12:39