Add delay to JS animated text? - javascript

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);

Related

Fading a tag in, fading it out and then changing the text before repeating the process

I have an tag that is having its contents changed via jquery and then faded in and out (using the velocity js library) utilizing the setInterval function. When I run this it tends to work fine for about 30 seconds before it starts to malfunction and jquery starts to change the contents of the tag before the tag has faded out.
Here is the Javascript code
let counter = 0;
function chooseWord() {
let words = ["foo", "bar", "foo"];
if (counter !== 2) {
counter += 1;
} else {
counter = 0;
}
return words[counter];
}
function refreshText() {
$("#div").text("Foo " + chooseWord())
.velocity("fadeIn", {
duration: 2500
})
.velocity("fadeOut", {
delay: 1500,
duration: 2500
});
}
$(document).ready(function() {
refreshText();
setInterval(function() {
refreshText();
}, 7000);
});
And here is my tag that is being used
<h1 class="foobar" id="div"></h1>
I've tried using Jquery's timer and I have the same issue. Does anyone know what the problem might be or maybe a different way of achieving what I want to do?
You just need to change the order of operations. I have moved the text-change command after fade-out. So the element fades out, and then jQuery will update its text.
$("#div")
.velocity("fadeIn", {
duration: 2500
})
.velocity("fadeOut", {
delay: 1500,
duration: 2500
})
.text("Foo " + chooseWord());
Fiddle: https://jsfiddle.net/Nisarg0/gLed0h1y/

JQuery FadeOut, Load and FadeIn

I've got a following code for fadeOut, load another content and fadeIn, but I've got a problem, that sometimes, when the load function is very fast, it switches the loaded content even before the timeline completely fadeOut, so the effect is a bit weird at this case. How can I prevent this?
Note
I want to load content immediately after click, so putting the load function into the first fadeTo callback function is not the solution. Thanks!
$(".switches li").click(function(evn) {
$(".switches li").removeClass("active");
$(evn.target).addClass("active");
$(".timeline").fadeTo(400, 0, function(){
$(this).css("visibility", "hidden");
});
$(".timeline").load("inc-timeline/"+evn.target.id+".html", function() {
$(this).fadeTo(400, 100, function() {
$(this).css("visibility", "visible");
if(evn.target.id === "data-girls") {
$(".data-girls-powered").fadeIn(400);
} else {
$(".data-girls-powered").fadeOut(400);
}
});
});
});
Use start option of .animate(), .finish()
// call `.load()` when `.fadeTo(400, 0)` starts
$(".timeline").finish().animate({opacity:0},{
start: function() {
// do asynchronous stuff; e.g., `.load()`
$(this).load("inc-timeline/"+evn.target.id+".html", function() {
// stop `.fadeTo(400, 0)` animation,
// start animating to `opacity:1`
$(this).finish().fadeTo(400, 1, function() {
// do stuff
});
});
},
duration: 400
});
$("button").click(function() {
// call `.load()` when `.fadeTo(400, 0)` starts
$(".timeline").finish().animate({opacity:0},{
start: function() {
var el = $(this);
// do asynchronous stuff; e.g., `.load()`
$.Deferred(function(dfd) {
setTimeout(function() {
dfd.resolveWith(el)
}, Math.floor(Math.random() * 3500))
}).promise().then(function() {
// stop `.fadeTo(400, 0)` animation,
// start animating to `opacity:1`
$(this).finish().fadeTo(400, 1, function() {
});
});
},
duration: 400
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click</button>
<div class="timeline">abc</div>
What about changing the duration of the load..to be longer than 400 milliseconds, would that help?

How do I do 3 animations in jQuery and loop them? (Timing is messed up.)

I have a three different transitions for fading out and fading in my 3 images.
animate1 = function() {
$('#changingImage').fadeOut('fast', function() {
$('#changingImage').attr("src","../files/others/image1.jpg");
$('#changingImage').fadeIn('fast');
});
};
I have this same function two more times, just replacing the 1s with 2s and 3s.
I call my three functions with this, repeating every 5 seconds:
animate1().delay(5000);
animate2().delay(10000);
animate3().delay(15000);
I'm new at jQuery, and I don't understand why the timing is wrong. All that happens is image2 (the original) gets replaced with image1, and that's it.
Try using the setTimeout() javascript function.
Documentation: http://www.w3schools.com/jsref/met_win_settimeout.asp
For example:
setTimeout(function(){ animate1(); }, 5000);
setTimeout(function(){ animate2(); }, 5000);
setTimeout(function(){ animate3(); }, 5000);
This basically 'pauses' your JavaScript/jQuery code for 5 seconds before running the function and continuing.
.delay() does not repeat an event, it just delays its execution. You need .setInterval() if you want to repeat an event based on a given interval:
window.setInterval(function(){
setTimeout(animate1, 1000);
setTimeout(animate2, 500);
}, 5000);
Demo: https://jsfiddle.net/erkaner/bfb7jgaL/1/
Yay! I figured it out with a bunch of help.
var animations = function() {
setTimeout(function() {
animate1();
console.log("Animation 1")
}, 5000);
setTimeout(function() {
animate2();
console.log("Animation 2")
}, 10000);
setTimeout(function() {
animate3();
console.log("Animation 3")
}, 15000);
};
setInterval(animations, 15000);
Hi i have a suggestion for you in case that you have more than this 3 image so you will create a new function for it ?
so what about to use only 1 function that will call it self with an attribute that define image name as it is the only thing is changing every time so you can use this better and less code ,you have just the n value will change every time will increase and the max value witch define how many image you want
//if you want to set this animation for more than 3 image just change the max value
var max=3;
setTimeout(function(){ animate(2); }, 5000);
animate = function(n) {
$('#changingImage').fadeOut('fast', function() {
if(n<=max){
$('#changingImage').attr("src","http://www.imacros-scripts-for-free.is-best.net/image"+n+".jpg");
$('#changingImage').fadeIn('fast');
if(n==max){n=1}else{n++;}
setTimeout(function(){ animate(n); }, 5000);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="changingImage" src="http://www.imacros-scripts-for-free.is-best.net/image1.jpg" width="200px">

Automatically move div with javascript on delay

I have the below piece of code that moves a onto the screen when ?added is in the URL which works great. I now need to add a piece of code to it that then moves the back over after 5 seconds. I have noticed there's a delay function but I'm not sure how to add it into the code. Can anyone help? Many thanks!
$(document).ready(
function () {
if (document.URL.indexOf("?added") >= 0) {
$('#popout-left-menu-container')
.animate({
'right': '2px'
}, 300);
};
});
You can use the setTimeout function to delay something in javascript. Maybe like this:
$('#popout-left-menu-container').animate({'right':'2px'},300);
setTimeout(function(){
//This is animation that runs after 5 seconds. You can use it to move the block back.
//You have to set your parameters yourself here
$('#popout-left-menu-container').animate({'right':'0px'},300);
}, 5000);
$(document).ready(
function () {
if (document.URL.indexOf("?added") >= 0) {
setTimeout(function(){
$('#popout-left-menu-container')
.animate({
right:'2px'
},300);
},5000);
};
});
You should do it with .delay().
$("query").animate(firstAnimation, firstDuration).delay(milliseconds).animate(secondAnimation, secondDuration);

Passing an HTML Element into a Javascript Function

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

Categories