Jquery collision detection for divs

I am trying to learn some programs using jQuery. I have a div that measures 800 x 800 pixels. I have another 16 x 16 pixel div that I want to move within the larger using the arrow keys. The problem is that I cannot make it work correctly, can someone please tell me what I am doing wrong.

Moving to the left works, it stops the 16x16 div if the css attribute "left" is under 0px:

$(this).keydown(function(e) { if (e.which == '37' && ($('#p1').css('left') > "0px")) { $('#p1').css('left', '-=16px') } }); 

Moving to the right does not work, it stops the 16x16 div by 80 pixels on the left, no matter what value above 80 pixels I try:

 $(this).keydown(function(e) { if (e.which == '39' && ($('#p1').css('left') < '800px')) { $('#p1').css('left', '+=16px') } }); 

Also, moving up and down using a similar method does not work, the movement is limited incorrectly. Movement in all directions works fine without the arguments && .

+1
source share
2 answers

Taking a response from jermel, I also cleaned 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); } }); }); 
0
source

Your problem:

 css('left') < '800px') 

You compare strings instead of numbers;

Try:

 var left = parseInt($('#p1').css('left'),10); if (e.which == '39' && (left < 800)) {... 
+2
source

Source: https://habr.com/ru/post/1402213/


All Articles