Skip to content Skip to sidebar Skip to footer

What's Wrong With This Javascript Script?

Possible Duplicate: Why is this not working ? pushing a box using mouse pointer This is a script to push a box using mouse pointer and it only work when the box is pushed from th

Solution 1:

Problem lies in two places:

  1. You should not set both css attribute left and right at the same time, this would confuse the browser which should dictate the location. If you set one, set the other to null.

  2. See my comment below

I also slightly revised your script as arr[0] and arr[1] are not easy to read as they don't convey what they are, so I assign a variable to the array values for better readability.

Happy pushing.

var pushBox = function(e){
    var pageXRight = window.innerWidth - e.pageX;
    box.offsetRight = window.innerWidth - (box.offsetWidth + box.offsetLeft);

    if(arr.length < 2){
    arr.push(e.pageX);
    console.log(JSON.stringify(arr));
    } else {

    var previousX = arr[0];
    var newX = arr[1];

    if(previousX < newX){
                // add e.pageX <= box.offsetRight to ensure that mouse appearance to the right of the box would not push the boxif(e.pageX >= box.offsetLeft && e.pageX <= box.offsetRight){
        box.style.right = null;
        box.style.left = e.pageX + "px";
        }
    } elseif(previousX > newX){
        if(pageXRight >= box.offsetRight){
        box.style.left = null;
        box.style.right = pageXRight + "px";
        }
    }

    arr.shift(arr[0] , arr[1]);        
    }

    allTextbox.value = window.innerWidth;
    leftTextbox.value = box.offsetLeft;
    rightTextbox.value = box.offsetRight;
    pageXTextbox.value = e.pageX;
    pageXRightTextbox.value = pageXRight;
}

Post a Comment for "What's Wrong With This Javascript Script?"