NinjaCode
NinjaCode

Reputation: 79

Moving a div left and right continously

I've been trying to get this javascript animation to work for hours now, and I got nothing. The problem isn't getting my div box to move from left to right(or from top to bottom), it's the opposite of each case that I have trouble with it. Here's what I have so far(In addition, I have set boundaries set to keep my moving box contained within the view window so if it hits any one of sides, it should move to the opposite direction). Any help is awesome at this point.

Note: the next step is to create a bouncing effect for the box, but i'll worry about that once i get simple animation working.

      setInterval(function(){


    if(parseInt(box.style.left) > parseInt(viewDim.width - 57)){

        box.style.left -= parseInt(box.style.left) - 2 + 'px';



    /* } else if(parseInt(box.style.left) < 0){

        //debug_log("HIT!!");
        //parseInt(box.style.left) += 2 + 'px';

    } else if(parseInt(box.style.top) > parseInt(viewDim.height-58)){



    } else if(parseInt(box.style.top) < 0){*/



    } else {

        box.style.left = parseInt(box.style.left) + 2 + 'px';
        //box.style.top = parseInt(box.style.top) + 5 + 'px';
    } 

}, 20);

Upvotes: 1

Views: 10179

Answers (3)

nxasdf
nxasdf

Reputation: 1148

Although you have your solution now, I couldn't help myself from making complete code here.

The bouncing box bounces around inside the parent element. Tested in IE8, FF3, and Opera11.

Upvotes: 1

Eric Fortis
Eric Fortis

Reputation: 17350

This can give an idea, how to do it with jQuery

http://jsfiddle.net/rFkpy/

$('#myDiv').click(function() {
  $(this).animate({
    left: '+=250'
  }, 1500, "easeOutBounce", function() {
    // callBack
  });
});

Upvotes: 0

kirilloid
kirilloid

Reputation: 14304

Code like this always works for me:

var boxWidth = 57, delta = 2;
setInterval(function(){
  var left = parseInt(box.style.left);
  if(left >= parseInt(viewDim.width - boxWidth)){
    delta = -2;
  }
  if (left <= 0) {
    delta = 2;
  }
  box.style.left = left + delta + 'px';
}, 20);

Upvotes: 3

Related Questions