View Full Version : Trying to write a script to push a box using mouse pointer in Javascript

07-22-2012, 08:08 PM
I'm in a beginner in Javascript, and trying to write a script that allows the user to push a box left and right using mouse pointer.
I managed to work it out when the pointer touches the left side of the box, but i'm facing two problems here :

When the pointer gets inside the box, the box jumps to the new coordinate. I want the box to stay in it's position when the pointer gets inside the box.
I really can't figure it out when the mouse touches the right side of the box. I want the box to get pushed left. I've made a box.offsetRight property to help me out but just can't use it efficiently.

Here's a picture to demonstrate what i mean :

The "X" mark is where the pointer is. And heading toward the right side of the box. How to push the box to the left ?
Here's what i've tried to do (it didn't work of course) :


<title>Chase the box</title>
body {
position: absolute ;
width : 100px;
height : 100px;
background-color : blue;
margin-top: 500px;
<div id="box" class="css-box"></div>
<div class="css-textbox">
<p>All : <input id="allTextbox" type="text"></input></p>
<p>Left : <input id="leftTextbox" type="text"></input></p>
<p>Right : <input id="rightTextbox" type="text"></input></p>
<p>e.pageX(Left) : <input id="pageXTextbox" type="text"></input></p>
<p>e.pageX(Right) : <input id="pageXRightTextbox" type="text"></input></p>
<script type="text/javascript" src="script.js"></script>


var box = document.getElementById("box");
var allTextbox = document.getElementById("allTextbox");
var leftTextbox = document.getElementById("leftTextbox");
var rightTextbox = document.getElementById("rightTextbox");
var pageXTextbox = document.getElementById("pageXTextbox");
var PageXRightTextbox = document.getElementById("pageXRightTextbox");

Object.prototype.offsetRight = null;

var pushBox = function(e){

var pageXRight = window.innerWidth - e.pageX;
box.offsetRight = window.innerWidth - (box.offsetWidth + box.offsetLeft);
if (e.pageX >= box.offsetLeft){
box.style.left = e.pageX + "px";
} else if(pageXRight >= box.offsetRight){
box.style.right = pageXRight + "px";
allTextbox.value = window.innerWidth;
leftTextbox.value = box.offsetLeft;
rightTextbox.value = box.offsetRight;
pageXTextbox.value = e.pageX;
pageXRightTextbox.value = pageXRight;
box.addEventListener("mousemove" , pushBox);

I hope to find an answer using Javascript not Jquery.

07-22-2012, 10:40 PM
You need to wait until the page has loaded before setting all your element-variables.

<body onload="init()">

// script.js
var box, allTextbox; // etc.
Object.prototype.offsetRight = null;

var pushBox = function (e) { /* etc. */ }

function init() {
box = document.getElementById("box"); // etc.

box.addEventListener("mousemove" , pushBox);