Any Simpler way to Write this jQuery code [duplicate] - javascript

I thought it would be simple but I still can't get it to work. By clicking one button, I want several animations to happen - one after the other - but now all the animations are happening at once. Here's my code - can someone please tell me where I'm going wrong?:
$(".button").click(function(){
$("#header").animate({top: "-50"}, "slow")
$("#something").animate({height: "hide"}, "slow")
$("ul#menu").animate({top: "20", left: "0"}, "slow")
$(".trigger").animate({height: "show", top: "110", left: "0"}, "slow");
});

Queue only works if your animating the same element. Lord knows why the above got voted up but it will not work.
You will need to use the animation callback. You can pass in a function as the last param to the animate function and it will get called after the animation has completed. However if you have multiple nested animations with callbacks the script will get pretty unreadable.
I suggest the following plugin which re-writes the native jQuery animate function and allows you to specify a queue name. All animations that you add with the same queue name will be run sequentially as demonstrated here.
Example script
$("#1").animate({marginTop: "100px"}, {duration: 100, queue: "global"});
$("#2").animate({marginTop: "100px"}, {duration: 100, queue: "global"});
$("#3").animate({marginTop: "100px"}, {duration: 100, queue: "global"});

I know this is an old question, but it should be updated with an answer for newer jQuery versions (1.5 and up):
Using the $.when function you can write this helper:
function queue(start) {
var rest = [].splice.call(arguments, 1),
promise = $.Deferred();
if (start) {
$.when(start()).then(function () {
queue.apply(window, rest);
});
} else {
promise.resolve();
}
return promise;
}
Then you can call it like this:
queue(function () {
return $("#header").animate({top: "-50"}, "slow");
}, function () {
return $("#something").animate({height: "hide"}, "slow");
}, function () {
return $("ul#menu").animate({top: "20", left: "0"}, "slow");
}, function () {
return $(".trigger").animate({height: "show", top: "110", left: "0"}, "slow");
});

You could do a bunch of callbacks.
$(".button").click(function(){
$("#header").animate({top: "-50"}, "slow", function() {
$("#something").animate({height: "hide"}, "slow", function() {
$("ul#menu").animate({top: "20", left: "0"}, "slow", function() {
$(".trigger").animate({height: "show", top: "110", left: "0"}, "slow");
});
});
});
});

A slight improvement on #schmunk's answer is to use a plain object jQuery object's queue in order to avoid conflicting with other unrelated animations:
$({})
.queue(function (next) {
elm1.fadeOut('fast', next);
})
.queue(function (next) {
elm2.fadeIn('fast', next);
})
// ...
One thing to keep in mind is that, although I have never run into problems doing this, according to the docs using the queue methods on a plain object wrapper is not officially supported.
Working With Plain Objects
At present, the only operations supported on plain JavaScript objects wrapped in jQuery
are: .data(),.prop(),.bind(), .unbind(), .trigger() and .triggerHandler().

You can also put your effects into the same queue, i.e. the queue of the BODY element.
$('.images IMG').ready(
function(){
$('BODY').queue(
function(){
$('.images').fadeTo('normal',1,function(){$('BODY').dequeue()});
}
);
}
);
Make sure you call dequeue() within the last effect callback.

Extending on jammus' answer, this is perhaps a bit more practical for long sequences of animations. Send a list, animate each in turn, recursively calling animate again with a reduced list. Execute a callback when all finished.
The list here is of selected elements, but it could be a list of more complex objects holding different animation parameters per animation.
Here is a fiddle
$(document).ready(function () {
animate([$('#one'), $('#two'), $('#three')], finished);
});
function finished() {
console.log('Finished');
}
function animate(list, callback) {
if (list.length === 0) {
callback();
return;
}
$el = list.shift();
$el.animate({left: '+=200'}, 1000, function () {
animate(list, callback);
});
}

Animate Multiple Tags Sequentially
You can leverage jQuery's built-in animation queueing, if you just select a tag like body to do global queueing:
// Convenience object to ease global animation queueing
$.globalQueue = {
queue: function(anim) {
$('body')
.queue(function(dequeue) {
anim()
.queue(function(innerDequeue) {
dequeue();
innerDequeue();
});
});
return this;
}
};
// Animation that coordinates multiple tags
$(".button").click(function() {
$.globalQueue
.queue(function() {
return $("#header").animate({top: "-50"}, "slow");
}).queue(function() {
return $("#something").animate({height: "hide"}, "slow");
}).queue(function() {
return $("ul#menu").animate({top: "20", left: "0"}, "slow");
}).queue(function() {
return $(".trigger").animate({height: "show", top: "110", left: "0"}, "slow");
});
});
http://jsfiddle.net/b9chris/wjpL31o0/
So, here's why this works, and what it's doing:
The call to $.globalQueue.queue() is just queueing a call to your tag's animation, but it queues it on the body tag.
When jQuery hits your tag animation in the body queue, your tag's animation starts, on the queue for your tag - but the way the jQuery animation framework works, any custom animation callback causes a tag's animation queue (the body's in this case) to halt, until the custom animation calls the passed-in dequeue() function. So, even though the queues for your animated tag and body are separate, the body tag's queue is now waiting for its dequeue() to be called. http://api.jquery.com/queue/#queue-queueName-callback
We just make the last queued item on the tag's queue a call to continue the global queue by calling its dequeue() function - that's what ties the queues together.
For convenience the globalQueue.queue method returns a this reference for easy chaining.
setInterval
For the sake of completeness, it's easy to land here just seeking an alternative to setInterval - that is you're not so much looking to make separate animations coordinate, as just fire them over time without the strange surge ahead in your animation caused by the way newer browsers will postpone animation queues and timers to save CPU.
You can replace a call to setInterval like this:
setInterval(doAthing, 8000);
With this:
/**
* Alternative to window.setInterval(), that plays nicely with modern animation and CPU suspends
*/
$.setInterval = function (fn, interval) {
var body = $('body');
var queueInterval = function () {
body
.delay(interval)
.queue(function(dequeue) {
fn();
queueInterval();
dequeue(); // Required for the jQuery animation queue to work (tells it to continue animating)
});
};
queueInterval();
};
$.setInterval(doAthing, 8000);
http://jsfiddle.net/b9chris/h156wgg6/
And avoid those awkward blasts of animation when a background tab has its animations re-enabled by the browser.

This has already been answered well (I think jammus's answer is the best) but I thought I'd provide another option based on how I do this on my website, using the delay() function...
$(".button").click(function(){
$("#header").animate({top: "-50"}, 1000)
$("#something").delay(1000).animate({height: "hide"}, 1000)
$("ul#menu").delay(2000).animate({top: "20", left: "0"}, 1000)
$(".trigger").delay(3000).animate({height: "show", top: "110", left: "0"}, "slow");
});
(replace 1000 with your desired animation speed. the idea is your delay function delays by that amount and accumulates the delay in each element's animation, so if your animations were each 500 miliseconds your delay values would be 500, 1000, 1500)
edit: FYI jquery's 'slow' speed is also 600miliseconds. so if you wanted to use 'slow' still in your animations just use these values in each subsequent call to the delay function - 600, 1200, 1800

I was thinking about a backtracking solution.
Maybe, you can define that every object here has the same class, for example .transparent
Then you can make a function, say startShowing, that looks for the first element which has the .transparent class, animate it, remove .transparent and then call itself.
I can't assure the sequence but usually follows the order in which the document was written.
This is a function I did to try it out
function startShowing(){
$('.pattern-board.transparent:first').animate(
{ opacity: 1},
1000,
function(){
$(this).removeClass('transparent');
startShowing();
}
);
}

Use the queue option:
$(".button").click(function(){
$("#header").animate({top: "-50"}, { queue: true, duration: "slow" })
$("#something").animate({height: "hide"}, { queue: true, duration: "slow" })
$("ul#menu").animate({top: "20", left: "0"}, { queue: true, duration: "slow" })
$(".trigger").animate({height: "show", top: "110", left: "0"}, { queue: true, duration: "slow" });
});

Related

jQuery animation setup callback throws error

I want to implement a jQuery animation callback method progress or step,
but in either case I'm getting the following error:
NS_ERROR_IN_PROGRESS: Component returned failure code: 0x804b000f (NS_ERROR_IN_PROGRESS) [nsICacheEntry.dataSize]
I searched a lot but not able to find anything in context, I am kind of stuck here, please suggest what could cause this error?
In fiddle i tried with step and progress and its working there , but not able to get it worked in my code, I am just looking, has some one faced such kind of error in jquery animation?
The sample code is:
this.taskHandle.find('img').stop(true, true).animate({
//todo//
top: vtop, // this.taskHandle.outerHeight(),
//'top': 0 - $('.target.upper').height(),
width: 0,
opacity: 0
}, {
duration: 2000,
step: function(){
console.log('I am called');
}
},
$.proxy(function() {
// some css clearing method
}, {
// some further actions after animation completes
})
);
You have some semantic errors going on here. I'm going to repost your code, formatted for easier reading:
this.taskHandle.find('img')
.stop(true, true)
.animate(
{
//todo//
top: vtop , // this.taskHandle.outerHeight(),
//'top' : 0 - $('.target.upper').height(),
width : 0,
opacity : 0
},
{
duration:2000,
step: function() {
console.log('I am called');
}
},
$.proxy(
function() {
// some css clearing method
},
{
// some further actions after animation completes
}
)
);
First: animate() doesn't accept 3 parameters (at least not those 3 parameters). I'm not sure what you are trying to do with your css clearing method, but anything you wan't to happen after the animation is complete should be in the complete method that you add right next to the step method.
Second: $.proxy() needs to have the context in which you want it to run as the second parameter, not some other"complete"-function.
So here is a slightly modified example which works. You can try it yourself in this fiddle.
var vtop = 100;
$('div')
.stop(true, true)
.animate(
{
top: vtop,
width: 0,
opacity : 0
},
{
duration: 2000,
step: function() {
console.log('I am called');
},
complete: function () {
alert('complete');// some further actions after animation completes
}
}
);
You could use Julian Shapiro's Velocity.js, which animations are (arguable) faster than jQuery and CSS (read this for more)
It allows you to use callbacks such as :
begin
progress
complete
like :
var vtop = 100;
jQuery(document).ready(function ($) {
$('div').find("img").velocity({
top: vtop,
width: 0,
opacity: 0
}, {
duration: 2000,
begin: function (elements) {
console.log('begin');
},
progress: function (elements, percentComplete, timeRemaining, timeStart) {
$("#log").html("<p>Progress: " + (percentComplete * 100) + "% - " + timeRemaining + "ms remaining!</p>");
},
complete: function (elements) {
// some further actions after animation completes
console.log('completed');
$.proxy( ... ); // some css clearing method
}
});
}); // ready
Notice that you just need to replace .animate() by .velocity()
See JSFIDDLE

Animated arrow(s)

I'm using the following code to animate a div class arrow;
function animUp() {
$(".arrow").animate({
top: "0"
}, "slow", "swing", animDown);
}
function animDown() {
$(".arrow").animate({
top: "40px"
}, "slow", "swing", animUp);
}
$(document).ready(function() {
animUp();
});
Which works great and animates the arrow as intended. I've then added the class 'arrow' to another div with an arrow in to animate and they both stop animate down, long pause, animate up, long pause, animate down etc. Rather than the smooth animation of one arrow.
I've also tried having arrow and arrow2 and combining them in the script like this;
function animUp() {
$(".arrow, .arrow2").animate({
top: "0"
}, "slow", "swing", animDown);
}
function animDown() {
$(".arrow, .arrow2").animate({
top: "40px"
}, "slow", "swing", animUp);
}
$(document).ready(function() {
animUp();
});
With the same result as above. What else can I try to get them both animating smoothly?
jsFiddle - My html structure is using bootstrap
animations are added to a queue by default in jQuery to avoid queueing you should do the following:
function animUp() {
$(".arrow, .arrow2").animate({
top: "0"
}, {
duration: "slow",
queue: false,
easing: "swing",
complete: animDown
});
}
function animDown() {
$(".arrow, .arrow2").animate({
top: "40px"
}, {
duration: "slow",
queue: false,
easing: "swing",
complete: animDown
});
}
notice how instead of just passing in "slow" we now use an object
the following is from the jQuery site :: http://api.jquery.com/animate/
queue (default: true)
Type: Boolean or String
A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it.

javascript + jquery + setinterval + animation

I'm having a problem with setInterval and jquery animate. Here is my code:
function slides1() {
...
$("table#agah1").animate({
"left": first1
}, "slow");
$("table#agah2").animate({
"left": first2
}, "slow");
}
$(function () {
cyc = setInterval("slides1()", 3000);
});
When switch to another browser tab, and return after a time, the animation keep doing it without delay, for the time I've been away from the tab, and then act correct. I've added these also without any luck:
$(window).focus(function () {
jQuery.fx.off = false;
cyc = setInterval("slides1()", 3000);
});
$(window).blur(function () {
jQuery.fx.off = true;
window.clearInterval(cyc);
});
Newer versions of jQuery use requestAnimationFrame callbacks to handle effects, and browsers don't process those on hidden tabs.
In the meantime, your setInterval events are still happening, causing more animations to get queued up.
Rather than use setInterval to schedule the animations, use the "completion callback" of the last animation to trigger the next cycle, with a setTimeout if necessary.
function slides1() {
...
$("table#agah1").animate({
"left": first1
}, "slow");
$("table#agah2").animate({
"left": first2
}, "slow", function() {
setTimeout(slides1, 2000); // start again 2s after this finishes
});
}
$(function () {
setTimeout(slides1, 3000); // nb: not "slides1()"
});
This will ensure that there's a tight coupling between the interanimation delay and the animations themselves, and avoid any issues with setTimeout getting out of sync with the animations.

Javascript glow/pulsate effect to stop on click

I have the following Javascript to make a text link glow/pulsate continuously. This link reveals another section of the same page so I would like it to stop once the user has clicked on it.
<script type="text/javascript">
$(document).ready(function() {
function pulsate() {
$(".pulsate").animate({opacity: 0.2}, 1200, 'linear')
.animate({opacity: 1}, 1200, 'linear', pulsate);
}
pulsate();
});
</script>
So basically, I just need to know what I need to add here so that the effect stops once it has been clicked.
If the same link is clicked again, the revealed section of the page will hide - is it too much trouble to make the effect start again after a second click?
I look forward to an answer from you good people.
Scott.
Simply bind to the click event and call stop(). You should also ensure that the opacity has been restored to 1:
$(document).ready(function() {
function pulsate() {
$(".pulsate").animate({ opacity: 0.2 }, 1200, 'linear')
.animate({ opacity: 1 }, 1200, 'linear', pulsate)
.click(function() {
//Restore opacity to 1
$(this).animate({ opacity: 1 }, 1200, 'linear');
//Stop all animations
$(this).stop();
});
}
pulsate();
});
Here's a working jsFiddle.
The solution is pretty simple. Have your pulsate() function make sure that .pulsate doesn't have the class stop before doing its thing. If it does have that class, then the pulsate() function will simply animate the link back to full opacity, but not continue the pulsating.
James' example works as well, but I prefer my approach because his way binds the click event to .pulsate over and over again. This kind of thing may cause problems depending on what the rest of your page is doing.
Live example: http://jsfiddle.net/2f9ZU/
function pulsate() {
var pulser = $(".pulsate");
if(!pulser.hasClass('stop')){
pulser.animate({opacity: 0.2}, 1200, 'linear')
.animate({opacity: 1}, 1200, 'linear', pulsate);
}else{
pulser.animate({opacity:1},1200)
.removeClass('stop');
}
}
$(document).ready(function() {
pulsate();
$('a').click(function(){
$('.pulsate').addClass('stop');
});
});

How to run two jQuery animations simultaneously?

Is it possible to run two animations on two different elements simultaneously? I need the opposite of this question Jquery queueing animations.
I need to do something like this...
$('#first').animate({ width: 200 }, 200);
$('#second').animate({ width: 600 }, 200);
but to run those two at the same time. The only thing I could think of would be using setTimeout once for each animation, but I don't think it is the best solution.
yes there is!
$(function () {
$("#first").animate({
width: '200px'
}, { duration: 200, queue: false });
$("#second").animate({
width: '600px'
}, { duration: 200, queue: false });
});
That would run simultaneously yes.
what if you wanted to run two animations on the same element simultaneously ?
$(function () {
$('#first').animate({ width: '200px' }, 200);
$('#first').animate({ marginTop: '50px' }, 200);
});
This ends up queuing the animations.
to get to run them simultaneously you would use only one line.
$(function () {
$('#first').animate({ width: '200px', marginTop:'50px' }, 200);
});
Is there any other way to run two different animation on the same element simultaneously ?
I believe I found the solution in the jQuery documentation:
Animates all paragraph to a left style
of 50 and opacity of 1 (opaque,
visible), completing the animation
within 500 milliseconds. It also will
do it outside the queue, meaning it
will automatically start without
waiting for its turn.
$( "p" ).animate({
left: "50px", opacity: 1
}, { duration: 500, queue: false });
simply add: queue: false.
If you run the above as they are, they will appear to run simultaenously.
Here's some test code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(function () {
$('#first').animate({ width: 200 }, 200);
$('#second').animate({ width: 600 }, 200);
});
</script>
<div id="first" style="border:1px solid black; height:50px; width:50px"></div>
<div id="second" style="border:1px solid black; height:50px; width:50px"></div>
While it's true that consecutive calls to animate will give the appearance they are running at the same time, the underlying truth is they're distinct animations running very close to parallel.
To insure the animations are indeed running at the same time use:
$(function() {
$('#first').animate({..., queue: 'my-animation'});
$('#second').animate({..., queue: 'my-animation'});
$('#first,#second').dequeue('my-animation');
});
Further animations can be added to the 'my-animation' queue and all can be initiated provided the last animation dequeue's them.
Cheers,
Anthony
See this brilliant blog post about animating values in objects.. you can then use the values to animate whatever you like, 100% simultaneously!
http://www.josscrowcroft.com/2011/code/jquery-animate-increment-decrement-numeric-text-elements-value/
I've used it like this to slide in/out:
slide : function(id, prop, from, to) {
if (from < to) {
// Sliding out
var fromvals = { add: from, subtract: 0 };
var tovals = { add: to, subtract: 0 };
} else {
// Sliding back in
var fromvals = { add: from, subtract: to };
var tovals = { add: from, subtract: from };
}
$(fromvals).animate(tovals, {
duration: 200,
easing: 'swing', // can be anything
step: function () { // called on every step
// Slide using the entire -ms-grid-columns setting
$(id).css(prop, (this.add - this.subtract) + 'px 1.5fr 0.3fr 8fr 3fr 5fr 0.5fr');
}
});
}
Posting my answer to help someone, the top rated answer didn't solve my qualm.
When I implemented the following [from the top answer], my vertical scroll animation just jittered back and forth:
$(function () {
$("#first").animate({
width: '200px'
}, { duration: 200, queue: false });
$("#second").animate({
width: '600px'
}, { duration: 200, queue: false });
});
I referred to: W3 Schools Set Interval and it solved my issue, namely the 'Syntax' section:
setInterval(function, milliseconds, param1, param2, ...)
Having my parameters of the form { duration: 200, queue: false } forced a duration of zero and it only looked at the parameters for guidance.
The long and short, here's my code, if you want to understand why it works, read the link or analyse the interval expected parameters:
var $scrollDiv = '#mytestdiv';
var $scrollSpeed = 1000;
var $interval = 800;
function configureRepeats() {
window.setInterval(function () {
autoScroll($scrollDiv, $scrollSpeed);
}, $interval, { queue: false });
};
Where 'autoScroll' is:
$($scrollDiv).animate({
scrollTop: $($scrollDiv).get(0).scrollHeight
}, { duration: $scrollSpeed });
//Scroll to top immediately
$($scrollDiv).animate({
scrollTop: 0
}, 0);
Happy coding!

Categories

Resources