I’m a beginner in JavaScript, and trying to make a simple script that pushes a box using the mouse pointer, but unfortunately it isn’t working for some reason, I hope you can help me out.
(This script is really primitive, only pushes the box from the left till now).
index.html :
<html>
<head>
<title>Chase the box</title>
<style>
body {
}
.css-box{
width : 100px;
height : 100px;
margin : auto;
background-color : blue;
}
</style>
</head>
<body>
<div id="box" class="css-box"></div>
<script type="text/javascript" src="script.js"></script>
</body>
script.js :
var box = document.getElementById("box");
var pushBox = function(e){
if(e.pageX == box.offsetLeft){
box.style.left = box.style.left + 1 + "px";
}
};
document.addEventListener("mousemove" , pushBox);
box.style.leftis a string. And in JavaScript if you dostring + intthe int will be type casted to a string and you getstring + string. For instance, ifbox.style.leftis10pxyou get:And that will be the value of
box.style.left. That isn’t what you want…To solve this you can use
parseInt(), which parses a string into an int:And your if is only matching when the X position of the cursor is exactly the same pixel as
box.offsetLeft. That’s almost impossible, I don’t know what you are trying to do with that if?At least,
box.style.lefthas no value the first time. You need to set the value at first to0and then use the event.A working example will be: http://jsfiddle.net/WouterJ/enLwh/ (please note that I have added
position: relative;because we can’t use theleftproperty on the current position)Some more tips, since you are new to JS:
If you do something like this:
X = X + 12;You can short that up as:
X += 12;