Skip to content Skip to sidebar Skip to footer

Jquery Collision Detection For Divs

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

Solution 1:

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)) {...

Solution 2:

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



    });


});

Post a Comment for "Jquery Collision Detection For Divs"