Keep div on screen

0

I would like to know how to make a div animated (I have JQuery keydown function that moves a div) but div exits the screen and I would like it to be up to 20 px from the margins. I already exprimentei put this div (div1) inside another div (div2) and put position:relative and overflow:hidden in div2 but even then div1 exits div2. I have also exprimoi to do some validations of the div1 position but unfortunately without success.

PS: Use the arrow keys to move the div1.

I leave below my code:

$(document).keydown(function(e){
    
    //var pos = $(".box").position();

    switch (e.which){
    case 37:    //left arrow key
        $(".box").finish().animate({
            	left: "-=50"
        });
        break;
    case 38:    //up arrow key
        $(".box").finish().animate({
            top: "-=50"
        });
        break;
    case 39:    //right arrow key
        $(".box").finish().animate({
            left: "+=50"
        });
        break;
    case 40:    //bottom arrow key
        $(".box").finish().animate({
            top: "+=50"
        });
        break;
    }
});
.box{
        width: 100px;
        height: 100px;
        position: relative;
        margin: 200px auto 0;
        background: yellowgreen;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="box"></div>
    
asked by anonymous 28.09.2017 / 13:26

1 answer

1

I made an adjustment in your code to not leave the screen on the left side.

For the other directions just follow the same logic.

$(document).keydown(function(e){
    
    //var pos = $(".box").position();
    let pixels = 50;
    let margemMinima = 30;

    switch (e.which){
    case 37:    //left arrow key
        
        let novaPosicao = $(".box").offset().left - pixels;
        
        if(novaPosicao > margemMinima) {
          $(".box").finish().animate({
                left: "-=" + pixels
          });
        }
        break;
    case 38:    //up arrow key
        $(".box").finish().animate({
            top: "-=" + pixels
        });
        break;
    case 39:    //right arrow key
        $(".box").finish().animate({
            left: "+=" + pixels
        });
        break;
    case 40:    //bottom arrow key
        $(".box").finish().animate({
            top: "+=" + pixels
        });
        break;
    }
});
.box{
        width: 100px;
        height: 100px;
        position: relative;
        margin: 200px auto 0;
        background: yellowgreen;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="box"></div>
    
28.09.2017 / 15:00