How to animate blocks one after the other? - javascript

With this bit of JavaScript I hoped to animate some block element one after the other by adding CSS animation classes with a time out of 500 milliseconds.
Unfortunately it waits one time and all the boxes slide up at once after the one wait.
Here is the script so far:
var blocks = $('.block');
blocks.each(function(index, obj) {
var block = $(obj);
setTimeout(function() {
block.addClass('animated slideInUp');
}, 500);
});
So, how do I add these classes asynchronically so the boxes on the page will slide up one after the other?

You can consider the index of the each() loop so that in setTimeout() the time will be multiple of 500. With this the boxes will appear in each 500 milliseconds as the setTimeout() will have timeout time as 500, 1000, 1500, ... and so on.
var blocks = $('.block');
blocks.each(function(index, obj) {
var block = $(obj);
setTimeout(function() {
block.addClass('animated slideInUp');
}, 500*index);
});

Related

How to Delay The First FadeIn Event On Slider

I am currently modifying this piece of code as apart of a project, it works fine for what I need it to do, however I want a relatively short transition period,but the initial div element only display for a brief moment and the fade process starts.
I was wondering if anyone could help me to correct this. Ideally I would like to set the initial slider timeframe or delay it from triggering the process,
var divs = $('.fade');
function fade() {
var current = $('.current');
var currentIndex = divs.index(current),
nextIndex = currentIndex + 1;
if (nextIndex >= divs.length) {
nextIndex = 0;
}
var next = divs.eq(nextIndex);
current.stop().fadeOut(500, function() {
$(this).removeClass('current');
setTimeout(fade, 5000);
});
next.stop().fadeIn(500, function() {
$(this).addClass('current');
});
}
fade();
To delay the function fade() from starting right away just do:
var divs = $('.fade');
function fade() {
....
}
setTimeout(fade, 5000); //here is the only change
At the end of your code fade() is executed right away. Just add a timeout to it. 5000 is in milliseconds, just switch that to the delay time you want.
Apart from your question, if you wanted to apply the fade function to objects only after you clicked them, you could do this.
$('.fade').on('click',function(){//instead of click you could use any event ex. mouseover
fade();//call fade function
});

delay between animate.css animations

I'm kind of new to jQuery and I'm currently trying the following:
I'm using animate.css to animate a div. What I want to do now is to define a timing between fading in and fading out. For example:
Fade in > 3 sec delay > fade out
I'm using this function to dynamically add classes from animate.css to my object (#test).
$(document).ready(function () {
phase1('#test', 'bounceInLeft');
function phase1(element, animation) {
element = $(element);
element.addClass('animated ' + animation);
};
});
I'm trying to archive something like this:
phase1('#test', 'bounceInLeft');
3 sec delay
phase1('#test', 'bounceOutLeft');
1 sec delay
phase1('#test2', 'bounceInLeft');
.....
Any kind of help is really appreciated :) Thanks in advance!
Yes you setTimeout. Wrap your code within this section and adjust the timing with the amount of milliseconds that you want. This allows you to stagger code timings with multiple values..
This example will delay by three seconds, then one by five seconds..
setTimeout(function(){
// place your code in here
}, 3000);
setTimeout(function(){
// place your second bit of code in here
}, 5000);
Since you are using jQuery, you can use animation chains like that
(function($){
$(".move")
.animate({left:"+=200"},3000)
.delay()
.animate({left:"+=100"},3000);
})(jQuery);
See Example
Using jQuery chain events
$("#id").fadeIn(1000).delay(3000).fadeOut(1000);
This should work for you. All parameters specify time 1000=1Sec
http://jsfiddle.net/k8zq2fo6/
You can increase the chain
$("#id").fadeIn(1000).delay(3000).fadeOut(1000).delay(2000).fadeIn(1000).delay(3000).fadeOut(1000).delay(2000);
Try utilizing .queue()
$(function() {
// load `Animate.css`
$("style").load("https://raw.githubusercontent.com/"
+ "daneden/animate.css/master/animate.css");
// animation settings
var settings = [{
"bounceInLeft": 3000
}, {
"bounceOutLeft": 1000
}, {
"bounceInLeft": 3000
}];
$("#test").queue("bounce", $.map(settings, function(val, key) {
return function(next) {
var current = Object.keys(val)[0];
$(this)
// reset `className`
.attr("class", "")
// add `animated` , `current` `class`
.addClass("animated " + current);
// log `.queue("bounce")` iteration
console.log(this.className, current
, settings[key][current], $(this).queue("bounce"));
// "delay": `settings[key][current]` ,
// call `next` function in `.queue("bounce")`
setTimeout(next, settings[key][current]);
}
}))
.dequeue("bounce")
// do stuff when `.queue("bounce")` empty
.promise("bounce")
.then(function(elem) {
console.log(elem.queue("bounce"), "complete")
})
});
#test {
position: relative;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">abc</div>
<style></style>

setInterval running really slow

I made a website where I need to animate strings that are longer than the containing parent.
This is the website: Here
If you click on next, you can see multiple pages of breeders with long names, that need to animate from left to right, but this only happens after 10 or 15 seconds and it takes a long time for it to start.
Now I have checked my code and this is where I create my functions:
function newsTicker() {
console.log('newsTicker')
verifyLength();
$('.breeder').not('.short-breed-name').each(function() {
var breederNameWidth = $(this).find('.breeder_name').width();
var divBreederNameWidth = $(this).find('.breeder_name_div').width();
var diff = Math.max(parseInt(breederNameWidth - divBreederNameWidth),0);
// console.log('diff:',diff)
$(this).find('.breeder_name').animate({
marginLeft: -diff
}, 3000,
function(){
$(this).animate({
marginLeft : 0
},3000)
})
})
}
function verifyLength() {
// console.log('verifyLength')
$('.breeder.visible').each(function() {
// debugger
var breederNameWidth = $(this).find('.breeder_name').width() + 10;
var divBreederNameWidth = $(this).find('.breeder_name_div').innerWidth();
if(breederNameWidth < divBreederNameWidth) {
$(this).addClass('short-breed-name');
$(this).find('.breeder_name').css({'width':'100%','text-align':'center'})
}
})
}
And this is where I call newsTicker:
function breederAnimate(){
verifyLength();
newsTicker();
setInterval(newsTicker, 1000);
}
Why is it so slow when my times are between 1 and 3 seconds?
You should be calling setTimeout not setInterval because you only want your animation to run once. You're restarting your animations every second
Also, you should be cancelling existing setIntervals when you click next or previous

show and hide with delays on a loop but no animation

I have a jsfiddle for this
Jsfiddle
The problem is, I am trying to create a script that ones a button is clicked flashes an image (car lights) on and off for a period of time. It works fine, but in IE8 since the lights are png the animation for it is causing a black background and border as it blinks on and off. So I trying to duplicate the same thing, but without using animation.
In my jsfiddle, the first function for the first click div represents what i am trying to do without animation, but it is not repeating. The code:
$('.oneD').click(function(){
for (var i = 0; i <= 9; i++) {
$('.oneP').show();
setTimeout(function(){
$('.oneP').hide();
}, 1000);
}
});
The 2nd function is the one I already created that does work, but it has the animation:
$('.twoD').click(function(){
for (var i = 0; i <= 9; i++) {
$(".twoP").fadeIn(1000, function () {
$(".twoP").hide();
});
}
});
Keep in mind that the jsfiddle is just a simple mock not using images. I am just looking for the functionality in which i can incorporate this. I appreciate your time in helping me with this.
instead of setTimeout() use setInterval() and clearInterval() like this:
$('.oneD').click(function(){
$('.oneP').show();
var interval = setInterval(function(){
$('.oneP').hide();
}, 1000);
//*after a number of time or loop
interval.clearInterval();
});
setInterval() "Loop" throught the function it is given every number of millisecond you pass it. and clearInterval() stop the "Loop".
I'd do it like this :
$('.oneD, .twoD').on('click', function(){
for (var i=0; i<9; i++)
$('.'+this.className.replace('D', 'P')).delay(1000).show(0)
.delay(1000).hide(0);
});
FIDDLE
This uses a selector for both elements and the same event handler, then swaps out the D for a P in the showing and hiding.
As for using delay() and making this work, hide() and show() will work just as the animated jQuery methods if a value for the duration is passed, even if that value is zero.
Fiddle here: http://jsfiddle.net/HxFpr/
var i;
$('.twoD').click(function(){
i = 0;
loopFlash();
});
function loopFlash(){
if(i < 10){ // flash 5 times (1 on 1 off = 2 cycles)
$('.twoP').toggle();
var flashing = setTimeout(loopFlash,500);
}
i++;
}
Yet another solution for you.
No Animation - with single interval
With animation - pure jQuery
http://jsfiddle.net/x6Kpv/6/
var noAnimationHandler = function() {
setInterval(function() {
var $el = $('.oneP');
$el[$el.is(":visible") ? "hide" : "show"]();
}, 800);
};
var animationHanddler = function() {
$('.twoP').fadeIn(300, function() {
$(this).delay(150).fadeOut(300, animationHanddler);
});
}
$('.oneD').click(noAnimationHandler);
$('.twoD').click(animationHanddler);
Thanks

javascript thread

http://jsfiddle.net/andersb79/SNTb3/1/
In this example when you click run. The div is animated in after it got its 1000 hellos.
If i comment the for loop in the beginning out and comment in the other for loop the animation starts before the append is running.
But then the animation is not running smooth. Can you in some way make this happend or is it impossible in javascript.
I want it to load up the divDocument in the meantime it is animated in. I dont mean it should be live adding but I dont want it to mess upp the animation and I dont want to loose time by adding the 1000 records before the animation is started.
Hope that you understand my qustion.
If you're going to add 10000 elements in one go it will block any other activity until it has finished.
If you start the animation and then do the add, it's jerky because for a short while the system is busy adding the divs, and then suddenly it realises that it's running behind on the animation and it has to rush to catch up. Note that the animation does not get interleaved with the addition of the elements.
The best way to solve this is to add the elements in batches, using setTimeout to trigger the next batch each time.
The batching gives the background thread time to run any other events, such as the animation handlers.
See http://jsfiddle.net/alnitak/yETt3/ for a working demo using batching. The core of the sample is this:
var n = 0,
batch = 100;
function nextBatch() {
for (var i = 0; i < batch && n < 10000; ++i, ++n) {
$("#divDocument").append("<div>hello</div>");
}
if (n < 10000) {
setTimeout(nextBatch, 0);
}
}
setTimeout(nextBatch, 0);
which adds elements 100 at a time, with the setTimeout call allowing the event handling thread to jump in and process animations and other UI events.
For example you can use setTimeout
$(document).ready(function () {
$(".openWindow").click(function () {
setTimeout(function() {
var divToShow = $("#divDocument");
var windowWidth = $(window).width();
var leftOut = (windowWidth * -1);
var leftIn = windowWidth + 500;
divToShow.css({ left: leftIn });
divToShow.show();
divToShow.animate({ left: 0 }, 400, function () {
divToShow.addClass("visibleDiv");
});
}, 2000);
for (var i = 0; i < 10000; i++) {
$("#divDocument").append("<div>hello</div>");
}
});
});
If you want to run animation after that elements was add you must create function for append elements and in end of this function call animation. If you want run this as async you must use setTimeout(func, 0) for animation and for elements add.

Categories

Resources