Moving HTML object easily with Javascript

When I try to move the DIV using jquery using setTimeout it just works fine and moves smoothly like this:

setTimeout("moveObject()", 10);

function moveObject() {
     $('.object').css("left", parseInt($('#object').css("left")) + 1);
}

      

It moves like it moves in Flash, you know easily. But there are some problems with setTimeout which has 10ms, when the browser tab gets blurred, the timeout stops and doesn't do the job it has.

So I thought it would be nice to use JQuery animation to solve this problem. I changed the code to this:

$("#object").animate({left: parseInt($('#object').css("left")) + 100}, 1000, "linear", function() {} );

      

In the first code, the object moves 1px after 10ms. In the second code, the object is moved 100 pixels in 1000ms. So I think these two codes should do the same, but they don't.

The first code moves the object easily, but the second doesn't. There is some damage in the movement.

My question is, how can I move this object easily (without using a timeout)? and it would be great if I could set the speed for that. Note. I am not using HTML5, so I am looking for a solution that works with jquery and HTML

+3


source to share


3 answers


The solution for this question is this: requestAnimationFrame https://gist.github.com/mrdoob/838785



0


source


jQuery uses timeouts internally to animate, there is no other way to do this.
You generally get a better stream if you use timers Window.requestAnimationFrame

instead window.setTimeout

, as it is built for animation and has higher fidelity.

What you really need to do is look at libraries like Greensock's GSAP , or consider using CSS3 for animations, which will give you much smoother animations in most cases.

Also note that you are actually calling eval

in a function, when you pass a string to setTimeout that is being evaluated, you should just refer to the function



setTimeout(moveObject, 10);

      

and 10 milliseconds is a really low number which was the absolute minimum, HTML5 sets it to 4ms these days, but not all browsers follow that, only a few years ago most browsers couldn't go below 50ms.

+2


source


As adeneo mentioned, you should take a look at CSS3 animations. Here is a really good article on MDN about property conversion . Also take a look at the css transforms which should be helpful in your case.

To smoothly move an element, you only need to dynamically add its class below.

.move-right {
  transform: translate3d(100px, 0px, 0px);
  transition: all 1s linear;
}

      

I've put together a small example that you can use as a starting point: https://jsfiddle.net/5bo5c8st/3/

+2


source







All Articles