I have several jquery animations running, each of which will need to be somewhat dependent on the success of the others. Is there a way to reliably do so without nesting each animation in another? I've looked into the 'queue' method but I believe queue is true by default? I'm running into an issue where animations start to offset one another if they're lined up like so:
function moduleSwap(){
//animation 1
//animation 2
}
setInterval(moduleSwap, 1000);
I'm using setInterval to repeat the function over and over again. Any recommendations?
setInterval(function(int) {
if(int % 2 == 0)
animation_1();
else
animation_2();
}, 1000);
increase int through int ++ method and pass it on setInterval.Its swap automatically your animations.Tricky but works for me.
Related
I want to learn the JavaScript as well. and looking the various jQuery functions to their equivalent JavaScript.
I want to convert this jQuery function to its equivalent JavaScript functions? How can I do this?
$('.sample').stop().animate({
left: '-102px'
}, 1000);
In a nutshell, a jQuery animation is a recurring timer that changes one or more CSS properties on each timer tick.
In addition jQuery implements a tweening algorithm that calculates on each timer tick, whether the animation is ahead or behind schedule and adjusts so that the animation always completes in the exact time specified.
In addition jQuery implements an animation queue so that multiple animations can be chained together (start the next one when the previous one completes).
In addition jQuery supports easing functions which allow you to specify a non-linear animation that varies it's speed during the time according to a specific algorithm.
FYI, the jQuery javascript source code is fully available if you want more details. The core of the work is in a local function called doAnimation(), though much of the work is done in functions called step and update which can be found with the definition of jQuery.fx.prototype.
Here's another answer that shows a simple fade animation in pure javascript.
Here's a general tutorial on animation.
You can see a discussion of using a timer for an animation here.
You can see a discussion of tweening here.
Here's a javascript version of your specific animation:
// node is the DOM element to animate
// prop is the CSS property name to animate
// end is the CSS value to animate to (only supports px units)
// duration is the time of the animation in ms
// fn is an optional callback when the animation is done
// fn is called like this fn(node, arg)
// arg is an optional argument that is passed to the callback
// context is an optional argument that is the this pointer for the function
function animate(node, prop, end, duration, fn, arg, context) {
var stepTime = 20;
var startTime = new Date().getTime();
var start = parseInt(getComputedStyle(node).getPropertyValue(prop), 10);
if (typeof end === "string") {
end = parseInt(end, 10);
}
function step() {
// calc how much time has elapsed
var nextValue, done, portionComplete;
var timeRunning = new Date().getTime() - startTime;
if (timeRunning >= duration) {
nextValue = end;
done = true;
} else {
portionComplete = timeRunning / duration;
nextValue = ((end - start) * portionComplete) + start;
done = false;
}
// set the next value
node.style[prop] = nextValue + "px";
if (!done) {
setTimeout(step, stepTime);
} else {
if (fn) {
context = context || window;
fn.call(context, node, arg);
}
}
}
// start the animation
step();
}
Working demo: http://jsfiddle.net/jfriend00/Mc3xD/
For simplicity of understanding, this doesn't implement the .stop() part of your jQuery example as that would need a separate data structure to keep track of each animation timer running on a given object which can be seen in a more involved version that supports stop(): http://jsfiddle.net/jfriend00/mp4Yq/.
you remind me when i started learning js , and then was very happy to find jquery , anyway i dont know why you are doing vice versa , but to answer you question
Animation in javascript can be used using setInterval function with changing the top , left .. etc attributes over a very small amount of time ( usually 24 milli secconds ) which to the human eye are like a stream and not like seperate shots of positions , also you may consider using pure css3 , however a function like this may be used
var position,ratio,time,mytimer;
document.getElementById("hi").style.left=0;
function animate_left(position,time)
{
ratio=position/time;
if(parseInt(document.getElementById("hi").style.left)<=position)
{
document.getElementById("hi").style.left=(parseInt(document.getElementById("hi").style.left)+ratio*100).toString()+"px"
}
else
{
clearInterval(mytimer)
}
}
function animate(value1,value2)
{
mytimer=setInterval(function(){animate_left(value1,value2)},10) //where 10 is minimum smooth animation factor for human eye
}
animate(600,1000);
http://jsfiddle.net/prollygeek/er67f/6/
I've background image and by using small javascript code, it moves from right to left.
HTML code
<div id="clouds_image"></div>
Javascript code
var g=0;
var speed=30;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
scroller=setTimeout(function(){rollClouds()},speed);
}
window.addEventListener?
window.addEventListener('load',rollClouds,false):
window.attachEvent('onload',rollClouds);
But i've noticed that, with time my PC CPU memory usage increased ! causing overload on my pc and if i disabled that javascript code, it back to normal.
My question
so i think i need to modify this javascript code that it not keep working forever, i mean, i want to make it to repeat that action only 5 times then stop , maybe i need to define value of g but i'm not good in javascript so any help ~ Thanks.
You need to use a variable to count how many times that function was executed, and use setInterval instead of setTimeout: See example
http://jsfiddle.net/EQDjx/206/ (my counter start from 100 and goes down to 0)
for a more nice effect i recomand you to use jquery. See animate function
http://api.jquery.com/animate/
var g = 1000;
var speed=300;
var counter = 100;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
if (counter < 1) clearInterval(interval);
}
interval = setInterval(function(){rollClouds()}, speed)
A cleaner solution might be to use jQuery to move the background:
function moveClouds() {
$("#clouds_image").css({left:"-2000px"});
$("#clouds_image").animate({left:"2000px"},10000);
}
Then you might set an interval to trigger it every x milliseconds.
setInterval(moveClouds,10000)
JSFiddle is here: http://jsfiddle.net/qXpVX/
I'm creating a game with jQuery, and I want my character to move automatically until it hits a boundary. Here is my movement code in right direction:
if (e.keyCode === 39 && (p1_left < 784)) {
$('#p1').rotate(0);
setInterval ( function() {
$('#p1').animate( { left: "+=16px", }, 50); }, 50);
}
This moves my character indefinetely to the right, and I haven't figured out myself how to create a stopper.
EDIT: Updated code snippet, Added jsfiddle http://jsfiddle.net/BjCeq/
You never actually increase pl_left so the loop will just run forever:
while (p1_left <= 784) {
pl_left+=16;
$('#p1').css('left', p1_left);
}
However, this is not going to animate the movement of your character, it will appear to just jump to the end point. For this reason it is kind of pointless to loop. What you probably want is either to use setTimeout to move every second one position or something. Or, you could use animate with a callback function:
function moveLeft(theID){
$(theIE).animate({...},1000, function(){
if(/* keep moving */){
move_left(theID);
}
}
}
What you need is code that's continually called. Your code, as you've written it, is called once, and it performs all of its DOM manipulation at once. What you need is a setInterval or a setTimeout to trigger your code to call itself a certain number of milliseconds in the future, incrementing the css property each time. The easiest way to accomplish this is to simply use jQuery.animate, which runs those methods internally.
var $p1 = $('#p1');
if (e.keyCode === 39 && (p1_left < 784)) {
$p1.rotate(0);
$p1.animate({ 'left' : 784 });
}
Check out the jQuery animate docs for more information, including how to set options and run a callback function with each frame of the animation: http://api.jquery.com/animate/.
Scenario:
I want to create a jQuery controllable jackpot "spinner" that will rapidly sequence a number of random images through a div before settling on one, with the delay interval between each equal but changeable. For mockup purposes, I'm simply changing CSS color classes to a box, although in the final I'll use background images.
I thought this would be a no-brainer to do with a loop. I'm sure there's a more efficient way to do this, but guessed the below would work fine. However, I discovered I have no way to control the CSS color swap speed. This whips through the color class changes instantly and just shows the last one. What I'd like is a delay where indicated.
jQuery delay() doesn't seem to work when chained with addClass(), though it works fine with effects. So I tried using window.setTimeout, but as far as I can see, in this context it requires a kludgey function call. The code as written below executes all the function calls after the loop has run. Is this a closure issue? Don't want to use setInterval because these will be limited iterations.
Thanks for any advice!
for (var j= 9; j >= 0; j--) {
$('#box1').attr('class', 'boxes'); // strips all current classes, replaces them with class 'boxes', which has general CSS characteristics
var numRand = Math.floor(Math.random() * 6);
var randomClass = colorArray1[numRand]; // pull random class from an array of six choices
$('#box1').addClass(randomClass);
// Everything above here works fine, would like loop delay here
// Tried using straight-up setTimeout -- doesn't appear to like loops
window.setTimeout(outerFunc, 1000);
};
function outerFunc() {
alert('nobody here but us chickens!');
};
If you want to use .delay() with a method like .addClass(), you can add it to the queue with jQuery's .queue() method.
$('#box1').delay(1000)
.queue(function( nxt ) {
$(this).addClass(randomClass);
nxt(); // allow the queue to continue
});
Otherwise, if I get what you want, you could multiply the 1000 ms for the setTimeout() by the current value of j, so that each time the duration increases.
window.setTimeout(outerFunc, (1000 * j));
setTimeout and setInterval work differently in javascript to the way you want to use them.
Both functions take the function that you pass in and attach them to the window DOM object. Then, after the delay you have passed in has passed, and when there is no other script currently running, they get called from the window object.
To get the functionality you are after, you will need to convert your code so that the jQuery addclass call is inside the function you are passing to setTimeout.
Perhaps recursion would work?
// this code is not tested
var j = 9;
function myFunc() {
// code here
j--;
if(j >= 0) setInterval(myFunc, 1000);
}
I haven't used the queue class in jQuery myself (first I've heard of it, but it sounds cool). That might be the better answer, but this should be a decent alternative if the queue doesn't work as expected.
UPDATE: I just noticed that in your code it looks like you are expecting setTimeout to work like Thread.Sleep in .Net. setTimeout doesn't work that way. It works more like Thread.Start where your code continues on as soon as you call it.
I've got a masterpage with some nice UI (jQuery) features. One of these options is interefering with my embedded YouTube (or other alike-) objects. On each, in this case, setInterval event the embedded video stops displaying new frames (for like a second).
More detail:
I've got a "polaroid" gallery (in the header) with only 5 100x100 images in it (test: preloading has no effect on performance) and my gallery will show or hide them (fade-in / fade-out) after a period of time. (test: non-animated display:hide or display:block has no effect on performance).
After some testing and I've come to the conclusion that it isn't the "animated" showing or hiding of the pictures, but it's the interval itself (- since altering to display:hide or block had the same result). Perhaps it is my "gallery" "function" on itself ...
function poladroid() {
if (!galleryHasFocus) {
if (galleryMax >= 0) {
galleryCurrent++;
if (galleryCurrent > galleryMax) {
galleryCurrent = 0;
showPictures = !showPictures;
}
if (showPictures) {
$('#pic-' + galleryCurrent.toString()).show("slow");
}
else {
$('#pic-' + galleryCurrent.toString()).hide("slow");
}
}
}
if (!intervalSet) {
window.setInterval("poladroid()", 3000);
intervalSet = true;
}
}
It's not like my function is doing really awkward stuff is it? So, I was thinking I needed a more "loose" interval function.. but is there an option for it?
Ow.. almost forgot to mention it: FireFox and Chrome perform pretty good; using IE (what else) has the most performance problems.
There is no substitute for setInterval/setTimeout - these are the only ways of timing events in browser based ECMAScript.
Its not easy to grasp the real issue here, but I'm guessing the whatever you are triggering using setInterval is heavier than it has to be (as it is jQuery) - you should try to make this more efficient.
If you want an easy to use slideshow, take a look at http://github.com/oyvindkinsey/JsSlideshow - it has a demo here
By the way, do not use a literal as the first argument to setTimeout/setInterval, use a function reference
setInterval(poladroid, 3000);