Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to animate image from left to right?

I have a Bee image and I want to animate it using jQuery.

The idea is to move the image from left (outside of screen) to right (outside of screen) to create an effect like it's flying.

like image 941
Ganikkost Avatar asked Oct 31 '11 18:10

Ganikkost


People also ask

How do I create a transition in jQuery?

The jQuery animate() method is used to create custom animations. Syntax: $(selector).animate({params},speed,callback); The required params parameter defines the CSS properties to be animated.

How do you animate with relative values?

To change the left or right or top or bottom of an element with a relative value, we use +=value or -=value in the CSS property, so that it changes the value at the current position to the relative increment or decrement with respect to the current position with the value given in the CSS property.

Is jQuery slower for animations?

jQuery can be several times slower than CSS when talking about animations. CSS animations and transitions have the advantage of being hardware accelerated by the GPU, which is really good in moving pixels.

How you can use jQuery to animate a flash to the button?

The solution to Jquery To Animate A Flash To The Button Selected will be demonstrated using examples in this article. $("#someElement"). fadeOut(100). fadeIn(100).


1 Answers

Your bee needs to be absolutely positioned, something like this:

<div id="b" style="position:absolute; top:50px">B</div>

I've used a div here, but it could just as well be an <img> tag. As meo pointed out, don't forget the top attribute, because some browsers don't work without it. Then you can animate it:

$(document).ready(function() {
    $("#b").animate({left: "+=500"}, 2000);
    $("#b").animate({left: "-=300"}, 1000);
});

Here is a jsfiddle demo.

If you want to have a continuous animation as Hira pointed out, put the animation code in functions, make sure the left and right movement is the same, and use the onComplete option of animate() to call the next animation:

function beeLeft() {
    $("#b").animate({left: "-=500"}, 2000, "swing", beeRight);
}
function beeRight() {
    $("#b").animate({left: "+=500"}, 2000, "swing", beeLeft);
}

beeRight();

And the fiddle for that.

like image 76
uɥƃnɐʌuop Avatar answered Oct 11 '22 13:10

uɥƃnɐʌuop