Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a moving div restricted in an outside div?

So I have a div you move with your arrow keys, but how do I make it so it can't go outside the "border div"?

$(document).ready(function(){
  $(document).keydown(function(e) {
      switch (e.which) {
      case 37: // Left
        $("#cube").css("left", $("#cube").offset().left - 101);
        break;
      case 38: // Up
        $("#cube").css("top", $("#cube").offset().top - 11);
        break;
      case 39: // Right
        $("#cube").css("left", $("#cube").offset().left - 97);
        break;
      case 40: // Down
        $("#cube").css("top", $("#cube").offset().top - 7);
        break;
      }
  });
});

http://jsfiddle.net/SfKHN/

like image 882
user2291675 Avatar asked Nov 03 '22 22:11

user2291675


1 Answers

Here you go:- I tested in FF and Chrome and seems to be fine....

Demo

Probably this is not completely perfect but you can build on it. Key here is to get the margins of the parent right and make sure the cube's left/right/top/bottom doesn't go beyond it. Border width also should be considered. Another thing is your Step should be a multiple of its width/height(as it is a square)

$(document).ready(function(){
    $(document).keydown(function(e) {
        var cube = $("#cube");
        var leftMargin = 0;
        var rightMargin = $('#outside').position().left + $('#outside').width() - cube.width();
        var topMargin =0;
        var bottomMargin = $('#outside').position().top + $('#outside').height() - cube.height();
        switch (e.which) {
        case 37: // Left
                var newLeft = parseInt(cube.position().left - 50);
               if(leftMargin <= newLeft)
                {
                    cube.css("left", newLeft);
                }
            break;
        case 38: // Up
                var newTop = parseInt(cube.position().top - 50);
                if(topMargin <= newTop)
                {
                    cube.css("top",newTop);
                }
            break;
        case 39: // Right
                var newRight = (cube.position().left + 50);
                 if(rightMargin > newRight)
                {
                    cube.css("left", newRight);
                }
            break;
        case 40: // Down
                var newBottom = parseInt(cube.position().top + 50);
                if(bottomMargin > newBottom)
                {
                    cube.css("top", newBottom);
                }
            break;
        }
    });
});
like image 175
PSL Avatar answered Nov 11 '22 05:11

PSL