How do you append a div to a container once a second? - javascript

I'm trying to find a good way to append a div to a container one at a time. I don't want to append all the divs and have them fade in one at a time. The code below is not working. Without the for loop it appends one at a time. I tried the for loop to limit the amount of times div gets appended sequentially but it output 4 divs every second. I want it to output one div once a second, four times.
for(var i = 0;i < 4; i++){
setInterval(function(){
$(".output").append("<div class='odiv'>TEST</div>")
},1000)
}
css:
.odiv{
display: inline-block;
}
html:
<div class="output"></div>

Just use timeout instead of interval with time as function of current iteration index 1000 * i:
for (var i = 0; i < 4; i++) {
setTimeout(function () {
$(".output").append("<div class='odiv'>TEST</div>")
}, 1000 * i);
}
.odiv {
display: inline-block;
padding: 5px;
background: #EEE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="output"></div>

Use a counter in order to clear the interval:
var i = 0;
var myInterval = setInterval(function() {
if (i === 4) return clearInterval(myInterval);
$(".output").append("<div class='odiv'>TEST</div>");
i++;
},1000);

Your current code is running $('.output').append() four times each second. Here's a breakdown of what your current code is doing:
- Start a loop for 0,1,2,3
--- Loop 0
Append a div to `.output` every 1000 milliseconds.
--- Loop 1
Append a div to `.output` every 1000 milliseconds.
--- Loop 2
Append a div to `.output` every 1000 milliseconds.
--- Loop 3
Append a div to `.output` every 1000 milliseconds.
The result is 4 intervals appending the .odiv element every 1000 milliseconds.
You want to append a single .odiv element every 1000 milliseconds, for 4 seconds. To do this, create a function that appends a div each 1000 milliseconds and stop it after the 4th iteration.
var i = 0;
var appendDiv = setInterval(function() {
if (i === 4) {
// Stop the setInterval function from running
clearInterval(appendDiv);
} else (
$(".output").append("<div class='odiv'>TEST</div>")
)
// Increase the counter
i++
}, 1000)
Here's a working jsFiddle.

Related

How to cycle through each div's display property to "display:none" to "display:block" in an endless loop with setTimeout?

I have a div that shows gif image and I have 4 gif image to cycle through with different duration in an endless loop(gif should cycle through 1 2 3 4 then 1 2 3 4 endlessly)
My gifplayer div: Other than the first div the other 4 divs initial display property is set to none
<div id="gifplayer"><img id="gif1" class="gifimg" src="gif1.gif">
<div id="gifplayer"><img id="gif2" class="gifimg" src="gif2.gif" style="display:none;>
<div id="gifplayer"><img id="gif3" class="gifimg" src="gif3.gif" style="display:none;>
<div id="gifplayer"><img id="gif4" class="gifimg" src="gif4.gif" style="display:none;>
Each gif has a different duration and I would like to play one another in an endless loop. Below is my jQuery and it works but only for the first time and also only the first gif is playing as expected 2nd, 3rd and 4th gifs are abruptly ending:
jQuery:
$(document).ready(function() {
setTimeout(function(){
$("#gif1").css("display","none")
$("#gif2").css("display","block")
$("#gif3").css("display","none")
$("#gif4").css("display","none")
}, 16000);
setTimeout(function(){
$("#gif1").css("display","none")
$("#gif2").css("display","none")
$("#gif3").css("display","block")
$("#gif4").css("display","none")
}, 18000);
setTimeout(function(){
$("#gif1").css("display","none")
$("#gif2").css("display","none")
$("#gif3").css("display","none")
$("#gif4").css("display","block")
}, 67800);
setTimeout(function(){
$("#gif1").css("display","block")
$("#gif2").css("display","none")
$("#gif3").css("display","none")
$("#gif4").css("display","none")
}, 16000);
})
Use the Modulo operator % to reset a i counter back to 0
Use classList 's .remove() and .add() methods
Use data-* attribute to store a desired ms duration time and later read it in JS using Element.dataset
const gifify = (EL) => {
const IMGS = EL.querySelectorAll("img");
const tot = IMGS.length;
let i = 0;
(cycle = () => {
const IMG = IMGS[i];
const dur = IMG.dataset.duration || 100; // ms (Fallback to 100ms)
IMGS.forEach(EL => EL.classList.remove("show")); // Hide all
IMG.classList.add("show"); // Show one
i += 1; // Increment index
i %= tot; // Loop index
setTimeout(cycle, dur );
})();
};
document.querySelectorAll(".gifify").forEach(gifify);
.gifify img { display: none; }
.gifify img.show { display: block; }
Infinite cycle trough images with different duration:
<div class="gifify">
<img data-duration="300" src="//www.placehold.it/100x100/0bf?text=1">
<img data-duration="500" src="//www.placehold.it/100x100/fb0?text=2">
<img data-duration="400" src="//www.placehold.it/100x100/f0b?text=3">
<img data-duration="100" src="//www.placehold.it/100x100/b0f?text=4">
</div>

Rotating several images with different timings

I have three images side by side, left, middle and right. I want the first image on the left to change after 2 seconds, then the one in the middle to change 2 seconds later and then the one on the right to change 2 seconds after that. Then after another 2 seconds I want the first one on the left to change again and for the sequence to start all over again.
I've put together the javascript code for each image to have a certain start time and then a 6 second interval before changing again, this gives the effect I'm looking for.
The sequence works the first time round but when the first image is due to run through the sequence the second time round the whole thing seems to stick a bit and then all the images start changing together, as if they are all affecting one another. I don't know why this is since the code refers to each separately. Any help would be appreciated. Here's the code:
HTML Code:
<div>
<img id="mainImage" src="firstimage.jpg">
<img id="mainImage1" src="secondimage.jpg">
<img id="mainImage2" src="thirdimage.jpg">
</div>
Javascript Code:
<script>
var myImage = document.getElementById("mainImage");
var imageArray = ["image1.jpg","image2.jpg","image3.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
setTimeout(changeImage, 0000);
setInterval(changeImage,6000);
</script>
<script>
var myImage1 = document.getElementById("mainImage1");
var imageArray1 = ["image4.jpg","image5.jpg","image6.jpg"];
var imageIndex1 = 0;
function changeImage1() {
myImage1.setAttribute("src",imageArray1[imageIndex1]);
imageIndex1++;
if (imageIndex1 >= imageArray1.length) {
imageIndex1 = 0;
}
}
setTimeout(changeImage1, 2000);
setInterval(changeImage1,6000);
</script>
<script>
var myImage2 = document.getElementById("mainImage2");
var imageArray2 = ["image7.jpg","image8.jpg","image9.jpg"];
var imageIndex2 = 0;
function changeImage2() {
myImage2.setAttribute("src",imageArray2[imageIndex2]);
imageIndex2++;
if (imageIndex2 >= imageArray2.length) {
imageIndex2 = 0;
}
}
setTimeout(changeImage2, 4000);
setInterval(changeImage2,6000);
</script>
Solution:
For each
setTimeout(changeImage2, x);
setInterval(changeImage2,6000);
change to
setTimeout(function() {
setInterval(changeImage2,6000);
}, x);
Check here: https://jsfiddle.net/bstd3fqu/4/
Explanation:
setTimeout() doesn't make runtime to sleep for certain time. It simply set a timer to execute the mentioned function after certain time. So all setInterval() calls are executing at almost same time in your implementation. I am just setting the interval in the setTimeout function so that these setInterval() calls are executing at different times.

I want to animate 0 counting up to 100

I have made a 10 slide presentation and I'm pretty happy with it but it looks a little stale, I want to add some animations and nice effects in there.
I currently have some text that reads '100%' i would like the page upon load to be at zero and then quickly count up to 100.
How would I do this?
$(document).ready(function(){
var count = 0;
var counting = setInterval(function(){
if(count < 101) {
$('.text').text(count + '%');
count++
} else {
clearInterval(counting)
}
}, 10);
});

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

Transition positioning

I have some code that I would like to integrate into the a website and have it be in the middle of the screen. This code does some fading with Javascript. But I can't move it around the screen like I would like to. When I move it around it messes up the animation.
Here is the HTML
<!DOCTYPE html>
jQuery fade-ins with a JavaScript for() loop
<div id="elem0" class="toBeFaded">Here's the first message...</div>
<div id="elem1" class="toBeFaded">We have second one here...</div>
<div id="elem2" class="toBeFaded">And here's the third message...</div>
<div id="elem3" class="toBeFaded">OMG!!! Here's the fourth message!</div>
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/fadeCode.js" defer="defer"></script>
​
Javascript
$(function (){
var yourFade = 1, // the amount of time in seconds that the elements will fade in AND fade out
yourDelay = 2, // the amount of time in seconds that there will be a delay between the fade ins and fade outs
fadeTime = yourFade * 1000, //convert fade seconds to milliseconds (1000)
delayTime = yourDelay * 1000, // convert delay seconds to milliseconds (2000)
totalTime = fadeTime + delayTime, //3000 milliseconds...needed for all those delays we talked about
allElems, // find out exactly how many page elements have the 'toBeFaded' class (4)
elemNoFade, // Will help us find the last element represent the last element (3)
i,
fadingElem;
for (i = 0, allElems = $('.toBeFaded').length, elemNoFade = allElems - 1; i < allElems; i+=1) {
fadingElem = "#elem" + i;
if (i === 0) {
$(fadingElem).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
} else if (i === elemNoFade) {
$(fadingElem).delay(totalTime * i).fadeIn(fadeTime);
} else {
$(fadingElem).delay(totalTime * i).fadeIn(fadeTime).delay(delayTime).fadeOut(fadeTime);
}
} });​
and CSS
.toBeFaded {
display: none;
position:absolute;
font-size:70pt;
}​
and a link to jsfiddle
I'm not sure I see the problem. Take a look at this fiddle: http://jsfiddle.net/joplomacedo/6xfKN/375/

Categories

Resources