2

My purpose is to move a DIV (box) within BODY's limits with JavaScript. It consists of 4 buttons, each one of them move the DIV vertically and horizontally (minus and plus values passed by the OnClick events).

My code is as follows (it doesn't work :( ):

<style>

#box {
    z-index: 2;
    position: absolute; 
    top: 200px; 
    left: 300px;
    width: 100px; 
    height: 227px; 
    border: none;
}

</style>

<script>

function moveV(i) { 

    var block, vTop, vNum;

    block = document.getElementById('box').style;
    vTop = block.top; 
    vNum = parseInt(vTop); 

    vNum += i; 
    block.top = vNum + "px"; 
} 

</script>

<input type="button" id="btn1" class="btn" onClick="moveV(-20);">
<input type="button" id="btn2" class="btn" onClick="moveH(-20);">
<input type="button" id="btn3" class="btn" onClick="moveV(20);">
<input type="button" id="btn4" class="btn" onClick="moveH(20);">

<div id="box"></div>

Also, another problem is that I don't know how to make it stop once you reach the body limit. Should I put it in another DIV so the limits are "tangible"?

MoeSzislak
  • 137
  • 1
  • 4
  • 13

2 Answers2

3

It would be better to use jQuery, by the way with straight javascript it would be:

  • Read the Viewport Height and Width (or like this in jQuery);
  • get the object, not the style (block = document.getElementById('box'));
  • read block.offsetTop and block.offsetLeft instead of style.top and style.left;
  • before setting the new value, check that is larger than 0 and that the new value PLUS the box width and height is NOT over the Viewport's height or width, ;
  • set the style.top and style.left as you are doing, by adding "px";

> Running Demo

Community
  • 1
  • 1
Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
  • You Sir deserve a Medal! Awesome! Huge thanks! The more I learn the more I see true beauty in coding, well, everyone else's except my code, but still... Soo much obliged! – MoeSzislak May 27 '13 at 17:39
1

you can use jquery:

function moveV(i) { 
    $("#box").animate({top:"+="+i+"px"});
}
function moveH(i) { 
    $("#box").animate({left:"+="+i+"px"});
}

it works.

Faridzs
  • 672
  • 8
  • 23
  • I still don't know even the basics of JavaScript, it would be a miracle for me to understand jQuery, but thank you. Still, I'm gonna take note of the code, in fact it seems much more clear and neat than the larger version (JS). – MoeSzislak May 27 '13 at 17:41
  • @user1814469, we strongly suggest jQuery because it will take care of all the problems "under the hood", wrapping them to a user friendly interface (es. `offsetLeft` and `style.left`, in jquery are just `left` in both cases). Saying that you can't start with jQuery because you need to start with straight JS it's like saying that you can't drive a car with an automatic transmission, because you need to drive a manual one before... if it is to learn, yes, but not because it's easier ;) hope that helps – Andrea Ligios May 27 '13 at 23:23