Skip to content Skip to sidebar Skip to footer

Why Is This Not Working ? Pushing A Box Using Mouse Pointer

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 guys can

Solution 1:

A JQuery version but accomplishes the same as you're trying to do

http://jsfiddle.net/3mxC3/1/

The main problem I can see with your script is that e.pageX == box.offsetLeft would mean that it's only going to be triggered when the pageX is exactly the offsetLeft.

The mousemove event won't be firing every pixel so this approach won't work. The easiest way to accomplish it is to set the mousemove onto the actual box instead (so it'll only fire if the user mouse overs the box)

Secondly, setting the left attribute on the box was doing nothing as the left/right-ness was being set by the margin: auto. Changing this to position: absolute makes it actually pay attention to the left attribute.


Solution 2:

box.style.left is a string. And in JavaScript if you do string + int the int will be type casted to a string and you get string + string. For instance, if box.style.left is 10px you get:

'10px' + 1 + 'px'
  int typecasted to string
'10px' + '1' + 'px'
  create one string
'10px1px'

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:

box.style.left = parseInt(box.style.left) + 1 + "px";

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.left has no value the first time. You need to set the value at first to 0 and 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 the left property 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;


Solution 3:

You need to set a CSS position property other than static to the element so CSS left property can work.

.css-box{
     position: absolute;
     width : 100px;
     height : 100px;
     margin : auto;
     background-color : blue;
}

Solution 4:

Lastly you are better off adding stuff onload instead of having the script live in the body

Here is a script that lives in the head of the page, the rest of the issues are already solved by other ppl here

var pushBox = function(e){
    if(e.pageX >= box.offsetLeft){
        box.style.left = (parseInt(box.style.left,10) + 1) + "px";
    }
},box;
window.onload=function() {
  box = document.getElementById("box");
  document.addEventListener("mousemove" , pushBox);
}

Post a Comment for "Why Is This Not Working ? Pushing A Box Using Mouse Pointer"