In this writing, I will share with you how I create an running animation with JQuery library. First of all, I need to insert an image and set an id for it.
div id="runningdog"
img class="picture" src="image/dog.png" style = "width:200px" /
/div
Then I set some CSS attributes for my picture. To let it moving, at first, I had to set its absolute position
#runningdog {
position: absolute;
left: 0;
clear: both;
overflow: hidden;
}
When everything was all set, I looked for the usage of animate() function from W3School website to build my first function to move the picture go to the right.
function moveRight(){
$("#runningdog").animate({left: "+="}, 15000)
}
From the W3School says that the optional speed parameter can take the following values: "slow", "fast" or miliseconds to determine the duration of the effect. However, when I set this value at "slow", my dog moved like the Flash! In my opinion, you should try this value in milisecond for more desirable movement. However, I dont want my dog only moving from to the right, I wanted it move to the right side of the window then, it should move back to the leftside. That was why I had another moveLeft function, and these function would call each others when they finished
var W = window.innerWidth - 200;
// W will be the absolute limit on the right side of the screen that my picture will move.
function moveRight(){
$("#runningdog").animate({left: "+="+W}, 15000, moveLeft)
}
function moveLeft(){
$("#runningdog").animate({left: "-="+W}, 15000, moveRight)
}
Last but not least, I had to call my fuction to let the animation begin. I decided to call them when my page is completely loaded. However, you can try to call it when mouseover or onclick as well.
$(document).ready(function() {
moveRight();
});
Hope your guys enjoy my sharing.