Javascript setTimeout + loop - javascript

I try to loop some div's, and I have that code:
var first = ".first";
for (i = 0; i < 9999; i++) {
setTimeout(function () {
$(first).delay(500).animate({
"opacity": "1"
}, 1500);
$(first).delay(1500).animate({
"opacity": "0"
}, 1500);
$(".1").delay(4500).animate({
"opacity": "1"
}, 1500);
$(".1").delay(1500).animate({
"opacity": "0"
}, 1500);
$(".2").delay(4800).animate({
"opacity": "1"
}, 1500);
$(".2").delay(1500).animate({
"opacity": "0"
}, 1500);
$(".3").delay(5300).animate({
"opacity": "1"
}, 1500);
$(".3").delay(1500).animate({
"opacity": "0"
}, 1500);
$(".4").delay(5600).animate({
"opacity": "1"
}, 1500);
$(".4").delay(1500).animate({
"opacity": "0"
}, 1500);
$(".5").delay(5900).animate({
"opacity": "1"
}, 1500);
$(".5").delay(1500).animate({
"opacity": "0"
}, 1500);
}, 6000);
}
I tried without setTimeout and effect was the same - divs was appeared and disappeared only in 1st loop. In each next loop they're appeared in random order. I know, that method is wrong, but I'm green with JavaScript and I have no idea how to do it correct. Someone can help me?

It is because the for loop keep attaching events and you are 9999 animations to the same element with no delay. They are just pounding on each other. The code makes no sense.
If you want the code to run in a loop, you can use a callback in one of the animations and call a function when it is done. Other option is to use a Interval, but that gets messy with timing events not being accurate and they can pile up.

It seems like you're trying to make the elements animate seemingly indefinitely by running a setTimeout timer a large number of times. For that you should instead use setInterval() to have the function run every 6 seconds.
So, instead of...
for (i = 0; i < 9999; i++) {
setTimeout(function () {
$(first).delay(500).animate({
"opacity": "1"
}, 1500);
// etc etc
}, 6000);
}
...do this:
setInterval(function () {
$(first).delay(500).animate({
"opacity": "1"
}, 1500);
// etc etc
}, 6000);
(note: no for loop.)
Demo: http://jsfiddle.net/57sYA/

I have found solution of my problem - setInterval
var licznik=0;
function show_anim(){
if(licznik!=9999){
$("#first").delay(500).animate({"opacity": "1"}, 1500);
$("#first").delay(1500).animate({"opacity": "0"}, 1500);
$("#1").delay(4500).animate({"opacity": "1"}, 1500);
$("#1").delay(1500).animate({"opacity": "0"}, 1500);
$("#2").delay(4800).animate({"opacity": "1"}, 1500);
$("#2").delay(1500).animate({"opacity": "0"}, 1500);
$("#3").delay(5300).animate({"opacity": "1"}, 1500);
$("#3").delay(1500).animate({"opacity": "0"}, 1500);
$("#4").delay(5600).animate({"opacity": "1"}, 1500);
$("#4").delay(1500).animate({"opacity": "0"}, 1500);
$("#5").delay(5900).animate({"opacity": "1"}, 1500);
$("#5").delay(1500).animate({"opacity": "0"}, 1500);
licznik++;
console.log(licznik);
}
}
$(document).ready(function(){
show_anim()
setInterval("show_anim()",12000);
});
Demo: http://jsfiddle.net/D5bxA/

Related

Changing html elements in a loop with animation

so I have a slideshow banner.. which will also have 1.A quote (div containing it is .msgSlide) 2.A buttton (div containing it is .btnSlide) when each slide appears.. my current snippet for just the 1st slide is->
$(function() {
$('.msgSlide').animate({left: "0%"}, 1000, function() {
$('.msgSlide')
.hide()
.html("<p>Dream Big.. Never give up.</p>")
.show()
.animate({left: "40%"}, 1000)
.animate({opacity: "0"}, 3000);
});
$('.btnSlide').animate({right: "0%"}, 2000, function() {
$('.btnSlide')
.hide()
.html("<button class='btn btn-lg btn-primary'>Learn more</button>")
.show()
.animate({right: "20%"}, 1000)
.animate({opacity: "0"}, 2000);
});
});
current snippet fiddle->http://jsfiddle.net/zzmm4fue/2/
I want to loop this pattern with different paragraphs & button texts depending on the no of slides!
Update-> i am trying something like this-> http://jsfiddle.net/zzmm4fue/3/ (not working though)
I think this is what you looking for .. maybe it will need some arrangement .. but you can start from here
$(function() {
var Divslength = $('.AnimateThis').length - 1;
loopanimation($('.AnimateThis').eq(0));
var count = 1;
setInterval(function(){
loopanimation($('.AnimateThis').eq(count));
if(count == (Divslength)){
count = 0;
}else{
count = count + 1;
}
},4000);
});
function loopanimation(el){
$('.AnimateThis').fadeOut(300).css('z-index',0);
el.css('z-index',1);
el.fadeIn(300 , function(){
el.find('.msgSlide')
.animate({left: "-500px"}, 0)
.hide()
.html("<p>Dream Big.. Never give up.</p>")
.show()
.animate({left: "50%"}, 1000)
.animate({left: "40%"}, 1000)
.animate({opacity: "0"}, 3000)
.animate({opacity: "1"}, 0)
.animate({left: "-500px"}, 0);
el.find('.btnSlide')
.animate({right: "-500px"},0)
.hide()
.html("<button class='btn btn-lg btn-primary'>Learn more</button>")
.show()
.animate({right: "30%"}, 1000)
.animate({right: "20%"}, 1000)
.animate({opacity: "0"}, 3000)
.animate({opacity: "1"}, 0)
.animate({right: "-500px"},0);
});
}
Working Demo
Ok may be it was a basic problem that's why no one replied.. i have come up with the solution myself.. please suggest if u have a better solution
$(function() {
var msgValue=["<p>Dream Big.. Never give up.</p>",
"<p>Some quote i haven't looked up yet.</p>",
"<p>I am not so good with quotes.</p>"],
btnValue=["<button class='btn btn-lg btn-primary'>Learn more</button>",
"<button class='btn btn-lg btn-warning'>Learn more</button>",
"<button class='btn btn-lg btn-danger'>Learn more</button>"],
count=0;
function loop(count) {
$('.msgSlide')
.css({left:0, opacity:0})
.fadeIn(2000)
.html(msgValue[count]);
$('.msgSlide')
.animate ({ left: '30%', opacity: '1'}, 1500, 'linear').fadeOut(2000);
$('.btnSlide')
.css({right:0, opacity:0})
.fadeIn(2000)
.html(btnValue[count]);
$('.btnSlide')
.animate ({ right: '30%', opacity: '1' }, 1500, 'linear').fadeOut(2000,
function() {
loop(count);
});
count++;
if(count==msgValue.length){ count=0; }
}
loop(count);
});
working fiddle- http://jsfiddle.net/zzmm4fue/12/

jQuery CSS Opacity Animate

So I'm trying to create a simple fading slideshow with five slides that repeats when finished.
I feel like what I've got should work, but it's not.
<script type="text/javascript">
$(document).ready(function() {
function playslide(){
setTimeout(function(){
$("#slide-two").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 10000);
setTimeout(function(){
$("#slide-three").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 20000);
setTimeout(function(){
$("#slide-four").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 30000);
setTimeout(function(){
$("#slide-five").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 2000, 'swing')}, 40000);
}
playslide();
});
</script>
The idea is that the first slide will always have its opacity set to 1, so that when the last slide fades out, it's as if it's starting again. Each slide will hold for 10 seconds before fading out and after each slide fades in, the previous slide's opacity will be set back to 0 ready for the next time it repeats.
I hope it's not an obvious mistake. Apologies if it is...
Please why not use a .fadeIn() and .fadeOut() instead?
setTimeout(function () {
$("#slide-two").fadeIn(400, function () {
setTimeout(function () {
$("#slide-two").fadeOut(function () {
$("#slide-three").fadeIn(400, function () {
// So on...
});
}, 1000);
});
}, 1000);
Better to use these functions for doing it instead of you manually animating opacity.
https://jsfiddle.net/sk8ruo3u/
here's how I would do it
var list = ['.one','.two','.three','.four'];
$.each(list, function(index, value){
changeOpacity(value, index*1000);
});
function changeOpacity(target, timeout) {
setTimeout(function () {
$(target).animate({
opacity: 0.05
}, 1000);
}, timeout);
};

When reaching viewport point then troggle my sidebar

I need to be able to troggle my sidebar.
This works but I also need to hide the sidebar when reach viewport > 740px.
The troggle needs to work also. I came a far way but I think I have to combine these two to let it work properly.
Anyone knows hot to do this?
CHECK OUT MY FIDDLE PLEASE >
My script:
$('.troggler').toggle(
function() {
$('.right').animate({"right": "-400px"}, "slow");
$('.troggler').animate({"background-position": "-25px"}, "fast");
}, function() {
$('.right').animate({"right": "0"}, "slow");
$('.troggler').animate({"background-position": "0"}, "fast");
})
$(window).resize(function() {
if ($(window).width() < 740) {
$(".right").animate({"right": "-400px"}, "slow");
$('.troggler').animate({"background-position": "-25px"}, "fast");
}
else {
$('.right').animate({"right": "0"}, "slow");
$('.troggler').animate({"background-position": "0"}, "fast");
}
});
I guess the $(window).resize() fires multiple events while you ara resizing the window.
To solve this, you might wait for the resizing (dragging) complete.
// Basic Concept is ...
$(window).resize(function () {
if( ... event not fired ... ){
setTimeout(function(){
// toggle your navi
},500);
}
....
});
DEMO:http://jsfiddle.net/VseLR/13/
Your code could go like this:
function showNavi(){
$('.right').animate({"right": "0"}, "slow");
$('.troggler').animate({"background-position": "0"}, "fast");
}
function hideNavi(){
$('.right').animate({"right": "-400px"}, "slow");
$('.troggler').animate({"background-position": "-25px"}, "fast");
}
$('.troggler').toggle(function() {
showNavi();},
function() {
hideNavi();
});
function applyLayout() {
if ($(window).width() < 740) {
hideNavi();
}else {
showNavi();
}
}
var timer = 0;
var delayToCall = (function () {
return function (callback, ms) {
if (timer > 0) {
clearTimeout (timer);
}
timer = setTimeout(callback, ms);
};
})();
$(window).resize(function () {
delayToCall(function(){
applyLayout();
}, 500);
});
You might want to check this question:
JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?
Hope this helps.

$(this) in animate() callback but with setTimeout

jQuery docs explicitly state that
If supplied, the complete callback function is fired once the
animation is complete. This can be useful for stringing different
animations together in sequence. The callback is not sent any
arguments, but this is set to the DOM element being animated.
Hence, this works fine:
$("button").click(function () {
$(this).next("div").stop(true, true).animate({
"opacity": 1,
"top": "36px"
}, 600, function () {
$(this).fadeOut("slow", function () {
$(this).css({
"top": 0,
"display": "block",
"opacity": 0
});
});
});
});
$(this)'s next sibling that is a div is first animated in, and then with a callback it is faded out again. However...!
When using a setTimeout in the fallback, this won't work. See this fiddle.
$("button").click(function () {
$(this).next("div").stop(true, true).animate({
"opacity": 1,
"top": "36px"
}, 600, function () {
setTimeout(function () {
$(this).fadeOut("slow", function () {
$(this).css({
"top": 0,
"display": "block",
"opacity": 0
});
});
}, 2000);
});
});
I need to use $(this).next() though, because I will be having multiple buttons on the page. How can I keep the delay of 2s but still use the $(this) selector?
For jQuery's animating methods, you can use delay():
$("button").click(function () {
$(this).next("div").stop(true, true).animate({
"opacity": 1,
"top": "36px"
}, 600, function () {
$(this).delay(2000).fadeOut("slow", function () {
$(this).css({
"top": 0,
"display": "block",
"opacity": 0
});
});
});
});
JSFiddle
NOTE: The reason that setTimeout() didn't work for you, is because this isn't referring to the element that you think it is, it's referring to the window. To do that, you'll need to first create a reference to this:
JSFiddle
Also a little bit of magic. You can bind "this" to the timeout function.
http://jsfiddle.net/h6E6z/5/
setTimeout(function () {
$(this).fadeOut("slow", function () {
$(this).css({
"top": 0,
"display": "block",
"opacity": 0
});
});
}.bind(this), 2000);
You could always just store $(this) in a variable and use it in the timeout function (I use "$" in front of variables storing a dom element - that is of course totally optional, I just like it that way...):
$("button").click(function () {
$(this).next("div").stop(true, true).animate({
"opacity": 1,
"top": "36px"
}, 600, function () {
var $next_div = $(this);
setTimeout(function () {
$next_div.fadeOut("slow", function () {
$next_div.css({
"top": 0,
"display": "block",
"opacity": 0
});
});
}, 2000);
});
});

setTimeout not completely working

In the following code, the div animating in my moveit() function is waiting for the setTimeout() in the .click functions, but the p.font-size animation in moveit() is happening immediately upon the click. It's not waiting for the timeout. I'm sure it's a basic issue, but that's the level I'm at right now.
Thanks for any suggestions,
<script type="text/javascript">
$(document).ready(function(){
$("#no").click(function() {
$("#sleep").animate({"border-width": "10px"}, "fast");
$("#sleepanswer").animate({ opacity: 0 }, "fast");
$("p:.sleepquestion").replaceWith("That is too bad. Tonight you will sleep better.");
setTimeout(moveit, 2000);
});
$("#yes").click(function() {
$("#sleepanswer").animate({ opacity: 0 }, "fast");
$("p:.sleepquestion").replaceWith("That is great! A good night sleep is important.");
setTimeout(moveit, 2000);
});
});
</script>
<script type="text/javascript">
function moveit() {
$("#sleep").animate({"left": "10px", "width": "150px"}, "slow");
$("p.sleepquestion").animate({"font-size": "16px"}, "slow");
$("#sleepanswer").animate({ "left": "-9999px"}, "fast");
}
</script>
I think the problem may have been your use of .replaceWith(). That attempts to replace an element with another, but you've tried to replace an element with text. I think you just want to use .html() instead.
Also, you don't need to use the setTimeout() - you can use .delay() instead. And, I think your selectors p:.sleepquestion are probably not right. You can go with this:
<script type="text/javascript">
$(document).ready(function(){
$("#no").click(function() {
$("#sleep").animate({"border-width": "10px"}, "fast");
$("#sleepanswer").animate({ opacity: 0 }, "fast");
$("p.sleepquestion").html("That is too bad. Tonight you will sleep better.");
moveit();
});
$("#yes").click(function() {
$("#sleepanswer").animate({ opacity: 0 }, "fast");
$("p.sleepquestion").html("That is great! A good night sleep is important.");
moveit();
});
});
</script>
<script type="text/javascript">
function moveit() {
$("#sleep").delay(2000).animate({"left": "10px", "width": "150px"}, "slow");
$("p.sleepquestion").delay(2000).animate({"font-size": "16px"}, "slow");
$("#sleepanswer").delay(2000).animate({ "left": "-9999px"}, "fast");
}
</script>
I also changed .replaceWith() to .html() and changed p:.sleepquestion to p.sleepquestion.
Your function moveit could also be written like this by putting the timeout inside the function:
function moveit() {
setTimeout(function() {
$("#sleep").animate({"left": "10px", "width": "150px"}, "slow");
$("p.sleepquestion").animate({"font-size": "16px"}, "slow");
$("#sleepanswer").animate({ "left": "-9999px"}, "fast");
}, 2000);
}
I had the same issue with a function call in setTimeout() not working . I solved the issue by surrounding the function call in quotes.
For example:
$("#yes").click(function() {
$("#sleepanswer").animate({ opacity: 0 }, "fast");
$("p:.sleepquestion").replaceWith("That is great! A good night sleep is important.");
setTimeout("moveit()", 2000);
});

Categories

Resources