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) :
index.html
<html>
<head>
<title>Chase the box</title>
<style>
body {
}
.css-box{
position: absolute ;
top:20px;
width : 100px;
height : 100px;
background-color : blue;
}
.css-textbox{
margin-top: 500px;
}
</style>
</head>
<body>
<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>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
script.js
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.
Thanks.