$.each animation running separately - javascript

I'm trying to run each animation function one after the other instead of all at once.
This is what I've got so far:
$(document).ready(function(){
var bars = $('.bar');
bars.each(function(){
var widthpercent = $(this).attr("data-percent");
$(this).fadeIn();
$(this).animate({width:widthpercent},500);
});
});
I've tried using .delay() and setTimeout() in various combinations to no avail.
Could anyone point me in the right direction? Thank you!

It sounds to me like you're looking for animate's complete function. You can write a recursive function to keep calling the function in the complete function until all the items have been animated. To simplify: every time one element is animated, a callback is fired that animates the next element. That is the purpose of the complete parameter, so I'm certain that is what you're looking for.
Here's an example you can adapt to your specific needs.
Live demo here (click).
var $divs = $('div');
function animate(element) {
$(element).animate({height: '30px'}, {
complete: function() {
if (current < $divs.length-1) {
++current;
animate($divs[current]);
}
}
});
}
var current = 0;
animate($divs[current]);
Further, this same logic can be applied to your fadeIn. Just wrap fadeIn's callback around that logic, like this:
Live demo here (click).
var $divs = $('div');
function animate(element) {
$(element).fadeIn(function() { //now the animation is a callback to the fadeIn
$(element).animate({height: '70px'}, {
complete: function() {
if (current < $divs.length-1) {
++current;
animate($divs[current]);
}
}
});
});
}
var current = 0;
animate($divs[current]);
And here's your code: live demo here (click).
$(document).ready(function(){
var $divs = $('.bar');
function animate(element) {
$(element).fadeIn(function() { //you could unwrap this depending on what you're looking for
var widthpercent = $(element).attr("data-percent");
$(element).animate({
width:widthpercent,
duration: '500ms'
}, {
complete: function() {
if (current < $divs.length-1) {
++current;
animate($divs[current]);
}
}
});
}); //end fadeIn callback
}
var current = 0;
animate($divs[current]);
});

Try this:
var animate = function (el) {
return function () {
var widthpercent = el.data('percent');
el.fadeIn();
el.animate({
width: widthpercent
}, 500);
}
}
var bars = $('.bar');
bars.each(function (index) {
var $this = $(this);
setTimeout(animate($this), index * 500);
});
Fiddle

$(document).ready(function(){
var bars = $('.bar');
bars.each(function(i){
var widthpercent = $(this).attr("data-percent");
$(this).delay(i*800).animate({width:widthpercent,opacity:1,},500);
});
});
This will animate after delaying 800 * i milliseconds.
See this JSFiddle example.

Related

slider won't work properly

I am trying to animate my list item towards right but it animate all item towards right at once but I want it to be one after another ..here is my jQuery
var I,
total_slide = $('#slide li').length,
slide = $('#slide li');
function run() {
for (I = 1; I <= total_slide; I++) {
var total = total_slide - I
$(slide).eq(total).animate({
left: '700px'
}, 4000);
}
}
run()
You have to use setTimeout function to make pauses between animations:
function run(){
var timeout = 0, delay = 4000;
$("#slide li").each(function(){
var $li = $(this);
setTimeout(function(){
$li.animate({ left: 700 }, delay);
}, timeout);
timeout += delay;
});
}
Example
Also I would recommend to use CSS-animations whenever it's possible:
Example with CSS-animations

Set up a counter for a JavaScript timer loop based on number of images

What I would like to do is set each BannerImg element to display: none one at a time using a timer setup. Then, once I have looped through all BannerImg elements, I want to reset them to display: block. It's basically like a image rotator that I'm trying to make...but right now, I'm not sure how to target each BannerImg element one at a time--I am targeting them all at once, which is not what I want to do.
jQuery.noConflict();
(function($) {
$(document).ready(function() {
var BannerCount = $('BannerImg').length;
var intervalID = window.setInterval(function() {
$('.BannerImg').toggleClass("HideBannerImg");
}, 2000);
});
}(jQuery));
Use .eq(index). You'll probably want to cache your collection to make it faster:
(function($) {
$(document).ready(function() {
var $banners = $('.BannerImg');
var index = 0;
var intervalID = window.setInterval(function() {
$banners.eq(index).toggleClass("HideBannerImg");
index++;
// Check to see if we've hit the end of the collection
// If so, stop the interval.
if (index === $banners.length) {
clearInterval(intervalID);
}
}, 2000);
});
}(jQuery));
I'm kind of guessing you want something like this (correct me if I'm wrong):
setInterval(function () {
if ($('.BannerImg').last().hasClass('HideBannerImg')) {
$('.HideBannerImg').first().removeClass('HideBannerImg');
} else {
$('.BannerImg').not('.HideBannerImg').first().addClass('HideBannerImg');
}
}, 1000);
jQuery.noConflict();
(function($) {
$(document).ready(function() {
var iterator = 0;
var BannerCount = $('BannerImg').length;
var intervalID = window.setInterval(function() {
$('.BannerImg').eq(iterator).toggleClass("HideBannerImg");
iterator += 1;
if (iterator === BannerCount.length - 1) {
clearInterval(intervalID);
$('.BannerImg').removeClass("HideBannerImg");
}
}, 2000);
});
}(jQuery));
try this recursive function
var images = $('.BannerImg').each();
var hideImage = function(index){
images[index].toggleClass("HideBannerImg");
if(index < images.length-1)
setTimeout(function(){
hideImage(index++);
}, 2000);
}
hideImage(0);
After calling $('.BannerImg') you need to use jQuery's each to loop over each of the elements it selected.
jQuery.noConflict();
(function($) {
$(document).ready(function() {
$('.BannerImg').each(function() {
var $this = $(this);
var intervalID = window.setInterval(function() {
$this.toggleClass("HideBannerImg");
}, 2000);
});
});
}(jQuery));
Just note that this will toggle on and off over and over until you clear the interval.

jQuery animation for each element

I do not have much experience in animation on Jquery. I want to make a simple animation that will highlight my text line by line with the possibility of stopping. I know how to do something like this for one line but I have no idea how to deal with loop.
here is my code:
var lines = $('#page')[0].getClientRects();
for (var i=0, max = lines.length; i < max; i++)
{
$('#under_liner')
.queue(function() {
$(this).css('top', lines[i].bottom).dequeue();
})
.animate({
width: lines[i].right - lines[i].left
}, 1000 )
.queue(function() {
$(this).css('width', 0).dequeue();
});
}
and jsfiddle http://jsfiddle.net/mz03kfua/2
I don't know if this is exactly what you are looking for, but here's how I'd do it.
Make a function that does the underlining
Make a recursive call on animation callback
Create a global variable to keep count of the current underlined line
Add a boolean that stops the function when false
var lines = $('#page')[0].getClientRects();
var play = true;
var index = 0;
underlineLine();
$('button').click(function(){
play = !play
if(play){
underlineLine()
$(this).html("STOP")
}else{
$(this).html("CONTINUE")
}
})
function underlineLine(){
if(index >= lines.length) return
if(play){
$('#under_liner').css('top', lines[index].bottom).dequeue();
$('#under_liner').css('width','0px');
$('#under_liner').animate({
width: lines[index].right - lines[index].left
}, 1000, function(){
underlineLine(index++)
})
$('#under_liner').css('width', 0).dequeue();
}
}
HERE IS A FIDDLE WITH THE CODE.
Hope it helps.
http://jsfiddle.net/mz03kfua/4/
var lines = $('#page')[0].getClientRects();
var current = 0;
var element;
function animateLine() {
if(typeof lines[current] !== "object") {
return;
}
var line = lines[current];
element = jQuery("<div />", {"class": "under_liner"}).prependTo("#page");
element.css({top: line.bottom}).animate({width: line.width}, 1000, function() {
current++;
animateLine();
});
}
function stopLine(e) {
e.preventDefault();
element.stop(true);
}
jQuery(".stop").click(stopLine);
animateLine();

Stop .animate() on last image

I'm trying to make a gallery of images to scroll using up/down buttons. So far I go the animation but now I need to make it stop on the first and last image.
This is what I got so far, jsfiddle.net/sJDMq/47 (don't mind the buttons, I still need to work on them but they are there, top and bottom red boxes)
Thanks!
$(document).ready(function() {
$(".down_button").click(function () {
$(".scroll-products").animate({marginTop: '-=700px'}, 300);
});
$(".up_button").click(function () {
$(".scroll-products").animate({ marginTop: '+=700px' }, 300);
});
});
I wouldn't have done it this way but just going with what you started with I would just let this JS do the trick:
$(document).ready(function(){
var curIndex = 0;
var height = 700;
var maxHeight = 0;
var allImages = document.getElementsByClassName("sidebar_images");
for(var i=0; i<allImages.length; i++) {
maxHeight += allImages[i].offsetHeight;
}
var maxIndex = Math.ceil(maxHeight/height);
$(".down_button").click(function () {
if(curIndex < maxIndex) {
$(".scroll-products").animate({marginTop: '-='+height+'px'}, 300);
curIndex++;
}
});
$(".up_button").click(function () {
if(curIndex > 0){
$(".scroll-products").animate({ marginTop: '+='+height+'px' }, 300);
curIndex--;
}
});
});
I just updated your fiddle here.

Handling multiple setInterval calls

I am having trouble working out how to create a simple pop-and-drop effect for a class of divs. Since the onmouseover events of each of the items in this class are currently calling the same function, rapidly mousing between divs leaves the previous div stuck halfway through (if you mouse on and off from the bottom of the div, you'll see the effect I'm trying to produce).
My current approach also calls for me to replicate quite a bit of code to call the function from each individual div's event handlers, so if there's a way to wrap those up into one function I'd really like to know how. I'm sure there's a simple and efficient way to do all this, just can't seem to work it out.
jsFiddle example: http://jsfiddle.net/DvXDb/
Here's my code (script at the bottom):
div.bouncer{
position:relative;
top:50px;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
var thisDiv; var nextDiv; var selDiv;
var containerDivList = document.getElementsByClassName("container");
var containerArray = Array.prototype.slice.call(containerDivList);
var container1 = containerArray[0];
var container2 = containerArray[1];
var container3 = containerArray[2];
var container4 = containerArray[3];
container1.onmouseover = function () {
callPop(this.getElementsByTagName('div')[0]);
}
container1.onmouseout = function () {
callDrop(this.getElementsByTagName('div')[0]);
}
container2.onmouseover = function () {
callPop(this.getElementsByTagName('div')[0]);
}
container2.onmouseout = function () {
callDrop(this.getElementsByTagName('div')[0]);
}
container3.onmouseover = function () {
callPop(this.getElementsByTagName('div')[0]);
}
container3.onmouseout = function () {
callDrop(this.getElementsByTagName('div')[0]);
}
var relativeHeights = ['0px', '5px', '10px', '15px', '20px', '25px', '30px', '35px', '40px', '45px', '50px'];
var index = 10;
var intervalHandle1;
function callPop(thisDiv) {
clearInterval(intervalHandle1);
selDiv = thisDiv;
intervalHandle1 = setInterval(popImage, 5);
}
function callDrop(thisDiv) {
clearInterval(intervalHandle1);
selDiv = thisDiv;
intervalHandle1 = setInterval(dropImage, 5);
}
function popImage() {
selDiv.style.top = relativeHeights[index];
index--;
if (selDiv.style.top === '0px') {
index = 0;
}
}
function dropImage() {
index++;
selDiv.style.top = relativeHeights[index];
if (selDiv.style.top === '50px') {
index = 10;
}
}
Here's an example using jQuery, you really should be using a Framework for things like this. They simplify everything.
http://jsfiddle.net/AEJY9/
$(function () {
$('.bouncer').hover(
function () {
$(this).stop().animate({
top: 10
}, 500);
},
function () {
$(this).stop().animate({
top: 50
}, 500);
}
);
});

Categories

Resources