I'm trying to loop an "animation" of adding and removing classes:
function loading() {
$('#loading').removeClass().addClass('load0').delay(5000).removeClass().addClass('load1').delay(5000).removeClass().addClass('load2').delay(5000).removeClass().addClass('load3').delay(5000, loading);
}
loading();
Two problems:
It doesn't appear that removeClass() and addClass() can be queued with delay().
delay() doesn't appear to accept a callback function.
How can I do this?
var l = $('#loading'),
i = 0;
(function loading() {
l.removeClass().addClass('load' + i);
i = ++i % 4;
setTimeout(loading, 5000);
})();
Or we can encapsulate the variables too.
(function loading(l, i) {
l.removeClass().addClass('load' + i);
setTimeout(function() {
loading(l, ++i % 4);
}, 5000);
})($('#loading'), 0);
Modern browsers make this a little cleaner.
(function loading(l, i) {
l.removeClass().addClass('load' + i);
setTimeout(loading, 5000, l, ++i % 4);
})($('#loading'), 0);
You cannot use delay for non animating functions
Using setTimeout instead with your own callbacks might work out better.
If we're trying to loop animations why not loop animations using the .animate() with callbacks?
Example Fiddle:
http://jsfiddle.net/Culyx/fsxpZ/1/
The "arrow" in the fiddle used to be an image just a place holder div at the moment; but that should be another way of looping animations in jquery. Code for the looping animations:
$(document).ready(function () {
//looping bouncing arrow animation and speed controls
var arrowSpeed = 400;
bounceLeft = function () {
$(".arrow").animate({
left: "+=50px"
}, {
duration: arrowSpeed,
complete: bounceRight
});
}
bounceRight = function () {
$(".arrow").animate({
left: "-=50px"
}, {
duration: arrowSpeed,
complete: bounceLeft
});
}
bounceLeft();
});
Related
So I have the code below for a auto typing text animation. The text is in front of a image and I want people to see the full picture first and then the text starts to "type". I guess the best way is to add a 2-3 seconds delay before the text starts to animate but I'm not really sure how to do that.
Help would be very much appreciated. Thanks!
function cursorAnimation() {
$('#cursor').animate({
opacity: 0
}, 'fast', 'swing').animate({
opacity: 1
}, 'fast', 'swing');
}
$(document).ready(function() {
setInterval('cursorAnimation()', 1000);
});
var text = 'TEXT GOES HERE';
$.each(text.split(''), function(i, letter) {
setTimeout(function() {
$('#container').html($('#container').html() + letter);
}, 110 * i);
});
Adding some arbitrary delay is NOT the best way. You never know how much time an image will take to load on different kinds of networks, some are very fast, others might be very slow.
Instead you should fire your code on some event e.g. when the image has loaded. You can run your code on window load as an option as shown below:
function cursorAnimation() {
$('#cursor').animate({
opacity: 0
}, 'fast', 'swing').animate({
opacity: 1
}, 'fast', 'swing');
}
$(document).ready(function() {
setInterval('cursorAnimation()', 1000);
$(window).on("load", function(){
// do here tasks that you want to run after all page assets e.g. images have been loaded
showText();
});//window load()
});
function showText() {
var text = 'TEXT GOES HERE';
$.each(text.split(''), function(i, letter) {
setTimeout(function() {
$('#container').html($('#container').html() + letter);
}, 110 * i);
});
}
Try using setTimeout() function to call your function after some time i.e
$(document).ready(function() {
setTimeout(yourfunction(), 1000); //changes milliseconds as per your need.
})
https://www.w3schools.com/jsref/met_win_settimeout.asp
Generaly. It is done that you pack delayed code into callback and that callback you pass into setTimeout method. For preserving functionality while working in objects. I recomentd to call bind(this) on packaged callback.
setTimeout(function () {
console.log("Delayed message");
}.bind(this), 3000);
In your case
function cursorAnimation() {
$('#cursor').animate({
opacity: 0
}, 'fast', 'swing').animate({
opacity: 1
}, 'fast', 'swing');
}
$(document).ready(function() {
setInterval('cursorAnimation()', 1000);
});
var text = 'TEXT GOES HERE';
setTimeout(function () {
// delayed code
$.each(text.split(''), function(i, letter) {
setTimeout(function() {
$('#container').html($('#container').html() + letter);
}, 110 * i);
});
// end of delayed code
}.bind(this), 3000);
I am very new to jQuery, JavaScript, etc
I have been working on trying to get a couple of animations going:
Currently I have a partial working demo located here: http://jsbin.com/uwonun/64/
Thanks to jwags, the 2nd .animate() works.
I have been trying to implement the same animation effect so that I can replace the .slideDown().
My latest attempt to get it working can be found here: http://jsbin.com/OYebomEB/1/
Please be aware that as continu to work on this, the code will change.
function anim_loop(index) {
$(elements[index]).css({top: 0, display: 'none'}).animate({top: -75},1000, function() {
var $self = $(this);
setTimeout(function() {
$self.animate({top: $(window).height() + 10}, 1000);
anim_loop((index + 1) % elements.length);
}, 3000);
});
}
You set display:none, but never show it up after.
Use css('display','block') in your setTimeout(), before animate():
setTimeout(function() {
$self.css('display','block').animate({top: $(window).height() + 10}, 1000);
anim_loop((index + 1) % elements.length);
}, 3000);
});
You can make it appear smoothly by setting opacity:0 at the initialization, and opacity:1 in your second animate() ;)
Edit
To get the first loop working as the others, you have to display your elements before they render onscreen, by setting display:block before the animate() :
function anim_loop(index) {
$(elements[index]).css({top:-75, display: 'block'}).animate({top: '+0'},1000, function() {
var $self = $(this);
setTimeout(function() {
$self.animate({top: $(window).height() + 10}, 1000);
anim_loop((index + 1) % elements.length);
}, 3000);
});
}
I have a jQuery slideshow plugin that I am making though it has a setInterval() inside it which is not being called though if I move the contents of the setInterval() outside of the it then it works though it only runs once.
var gap = 3;
var duration = 0.5;
(function ($) {
$.fn.slideshow = function () {
return this.each(function () {
g = gap * 1000;
d = duration * 1000;
$(this).children().css({
'position': 'absolute',
'display': 'none'
});
$(this).children().eq(0).css({
'display': 'block'
});
setInterval(function () {
slide();
}, g);
function slide() {
$(this)
.children()
.eq(0)
.fadeOut(d)
.next()
.fadeIn()
.end()
.appendTo($(this).children().eq(0).parent());
}
});
};
})(jQuery);
$('.slideshow').slideshow();
HTML:
<div class='slideshow'>
<a>1</a>
<a>2</a>
<a>3</a>
<a>4</a>
</div>
Here is a fiddle with my plugin:
http://jsfiddle.net/Hive7/GrtLC/
The problem is this inside the slider function does not point to the object you think it points to.
setInterval($.proxy(function () {
slide.call(this);
}, this), g);
Demo: Fiddle
or better
setInterval($.proxy(slide, this), g);
Demo: Fiddle
Your problem is that this is always locally defined; by the time you get into the setInterval(), you've lost your original this (it's reset to the window object).
There are a few ways to get around this; the simplest is probably to copy this into a local variable.
http://jsfiddle.net/mblase75/GrtLC/5/
var gap = 3;
var duration = 0.5;
(function ($) {
$.fn.slideshow = function () {
return this.each(function () {
g = gap * 1000;
d = duration * 1000;
$this = $(this); // caches the jQuery object as a further optimization
$this.children().css({
'position': 'absolute',
'display': 'none'
});
$this.children().eq(0).css({
'display': 'block'
});
setInterval(function () {
slide($this); // pass $this into the function
}, g);
function slide($obj) {
$obj.children()
.eq(0)
.fadeOut(d)
.next()
.fadeIn()
.end()
.appendTo($obj.children().eq(0).parent());
}
});
};
})(jQuery);
$('.slideshow').slideshow();
Your code cannot work, because your callback is not bound to the this; try instead
var that = this;
setInterval(function () {
slide();
}, g);
function slide() {
$(that) ....
this inside slide function is not the slideshow. I make it work caching the object inside the each loop: http://jsfiddle.net/x7Jk8/
I'm trying to create an animation sequence with jQuery where one animation starts after the previous one is done. But I just can't wrap my head around it. I've tried to make use of the jQuery.queue, but I don't think I can use that because it seems to have one individual queue for each element in the jQuery array.
I need something like:
$('li.some').each(function(){
// Add to queue
$(this).animate({ width: '+=100' }, 'fast', function(){
// Remove from queue
// Start next animation
});
});
Is there a jQuery way to do this or do I have to write and handle my own queue manually?
You can make a custom .queue() to avoid the limitless nesting..
var q = $({});
function animToQueue(theQueue, selector, animationprops) {
theQueue.queue(function(next) {
$(selector).animate(animationprops, next);
});
}
// usage
animToQueue(q, '#first', {width: '+=100'});
animToQueue(q, '#second', {height: '+=100'});
animToQueue(q, '#second', {width: '-=50'});
animToQueue(q, '#first', {height: '-=50'});
Demo at http://jsfiddle.net/gaby/qDbRm/2/
If, on the other hand, you want to perform the same animation for a multitude of elements one after the other then you can use their index to .delay() each element's animation for the duration of all the previous ones..
$('li.some').each(function(idx){
var duration = 500;
$(this).delay(duration*idx).animate({ width: '+=100' }, duration);
});
Demo at http://jsfiddle.net/gaby/qDbRm/3/
The callback of .animate() actually accepts another .animate(), so all you would have to do would be
$(this).animate({ width: '+=100' }, 'fast', function(){
$(selector).animate({attr: val}, 'speed', function(){
});
});
and so on.
You could call the next one recursively.
function animate(item) {
var elem = $('li.some').eq(item);
if(elem.length) {
elem.animate({ width: '+=100' }, 'fast', function() {
animate(item + 1);
});
}
}
animate(0);
why not build up a queue?
var interval = 0; //time for each animation
var speed = 200;
$('li.some').each(function(){
interval++;
$(this).delay(interval * speed).animate({ width: '+=100' }, speed);
});
EDIT: added speed param
Thanks to everybody replying!
I thought I should share the outcome of my question. Here is a simple jQuery slideDownAll plugin that slides down one item at a time rather than all at once.
(function ($) {
'use strict';
$.fn.slideDownAll = function (duration, callback) {
var that = this, size = this.length, animationQueue = $({});
var addToAnimationQueue = function (element, duration, easing, callback) {
animationQueue.queue(function (next) {
$(element).slideDown(duration, easing, function () {
if (typeof callback === 'function') {
callback.call(this);
}
next();
});
});
};
return this.each(function (index) {
var complete = null,
easing = 'linear';
if (index + 1 === size) {
complete = callback;
easing = 'swing';
}
addToAnimationQueue(this, duration / size, easing, complete);
});
};
} (jQuery));
Not very well test, but anyways.
Enjoy!!
I know this has been answered, but it seems that none of the questions are relevant to exactly my point.. My code is below. I need to pass in either the variable $dynamicPanel in to the second function, or pass this in to the second function. Either way would be acceptable.
While we're at it, is there any way that I can wait some number of seconds to execute the FirstAnimation function without again using the animate() method.
$(document).ready(function FirstAnimation() {
var $dynamicPanel = $(".dynamicPanel");
$('.dynamicPanel').animate({
opacity: 0,
left: '100'
}, 5000, function () {
alert('first animation complete');
SecondAnimation(this);
});
});
function SecondAnimation(this) {
$(this).animate({
opacity: 1
}, 100, function () {
alert('second animation complete');
FirstAnimation();
});
};
this is a reserved word and can't be used as a parameter name. You should do this:
$(document).ready(function(){
FirstAnimation();
});
function FirstAnimation() {
//this function doesn't change, use your code
};
function SecondAnimation(elem) {
$(elem).animate({
opacity: 1
}, 100, function () {
alert('second animation complete');
setTimeout(function(){ //Delay FirstAnimation 7 seconds
FirstAnimation();
}, 7000);
});
};
Hope this helps. Cheers
What about changing SecondAnimation(this); to SecondAnimation($dynamicPanel);? It looks like it would do what you want.
Use SecondAnimation.apply(this).
this waiting can be done with jQuery.delay()
$(document).ready(function FirstAnimation() {
var $dynamicPanel = $(".dynamicPanel");
$dynamicPanel.animate({
opacity: 0,
left: '100'
}, 5000, function () {
alert('first animation complete');
SecondAnimation($dynamicPanel); // <--pass the proper variable ;)
});
});
function SecondAnimation(this) {
$(this).delay(5000).animate({ //<<-- wait five seconds
opacity: 1
}, 100, function () {
alert('second animation complete');
FirstAnimation();
});
};
however you can call the whole function recursive and pass the animation settings as paramaters from an array. So you reuse the function and only change the behaviour.
// store animationsettings in an array;
var animationSettings = [{opacity: 0, left: '100'},{ opacity: 1 }];
// initialize the startup index
var x = 1;
// cache selector
var $dynamicPanel = $(".dynamicPanel");
// single function
(function animate(){
x = x == 1 ? 0 : 1;//<--- toggle the index
$dynamicPanel.delay(x * 5000).animate(animationSettings[x],
1000,
function () {
animate(); // recursive call this function.
});
}());
fiddle here