I have a div that I want to move using the keyboard arrows using jquery, the problem is that I only give it moved to the right and it leaves the section where it has to be. The html and css of the exercise:
<section id="square">
<div id="hijo">
</div>
</section>
#square {
border: 1px solid black;
height: 300px;
margin: 20px auto;
position: relative;
width: 60%;
}
#square #hijo {
background-color: red;
position: absolute;
top: 0px;
left: 0px;
width: 50px;
height: 50px;
}
My jquery:
$(document).keydown(function(tecla){
$('#hijo').css('position', 'relative');
if (tecla.keyCode == 37) {
$('#hijo').animate({right: "+=10px"}, 'fast');
}else if(tecla.keyCode == 38) {
$('#hijo').animate({up: "+=10px"}, 'fast');
}else if(tecla.keyCode == 39){
$('#hijo').animate({left: "+=10px"}, 'fast');
}else if(tecla.keyCode == 40){
$('#hijo').animate({down: "+=10px"}, 'fast');
}
});
Note: I don't want to modify the html and css files if I don't do everything with jquery
With a
switch
and using theevent.which
to obtain the key that performed the event works correctly, it is a matter of adding and subtracting the pixels up and to the left (top
,left
), I leave you the example:I also leave you the example in your code version with the same concept as the
top
oneleft
I mentioned in case you need it:I'll tell you that in my example I left a commented line in the
JQuery
, since if you look in yourcss
you are giving it a positionabsolute
and then in yourJQuery
a positionrelative
. I hope this solution helps you. Greetings.Your keyboard event listener in document puts your container in competition with a lot of other things. I would narrow down the problem by declaring the listener on
#hijo
. In order for it to listen for keyboard events it has to be an elementfocusable
so I made it an input. There you will style it as best you can.The element's position is determined by its X and Y coordinates, in this case
left
ytop
. Defining conflicting properties forleft
andright
when the element's dimensions are fixed doesn't have much effect.Since you know the dimensions of the container, and those of the child, you know that in order for it not to come out, it must be true that
I would save the internal state of the element using data attributes. Depending on the key I modify the value but with the restriction that I put before.
PS: I used
key
instead ofkeyCode
. It is more intuitive because they are names.