Why first image in Array doesn't loop the first time around? - javascript

I am making a simple animation using javascript. Of course I could use the CSS keyframes, but that would not work for what I need this for, so no CSS solution please. I threw in a status div just so you see what I mean without actually having to see the images. JSfiddle below.
Anyway here is the HTML.
<div id="zero-walking"><img src="#" id="zeroImage"></div>
<div id="statusDiv"></div>
Here is the javascript
var index = 0;
var zero = document.getElementById("zeroImage");
var zeroArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png", "images/5.png", "images/6.png", "images/7.png", "images/8.png", "images/9.png", "images/10.png", "images/11.png"];
zeroAnimate();
function zeroAnimate() {
zero.setAttribute('src', zeroArray[index]);
index += 1;
if (index == zeroArray.length) {
index = 0;
}
var statusDiv = document.getElementById('statusDiv');
statusDiv.innerHTML = zeroArray[index];
}
setInterval(zeroAnimate, 700);
http://jsfiddle.net/r9zfg3jp/

This block:
index += 1;
if (index == zeroArray.length) {
index = 0;
}
Should be at the very end of the function.
Your problem is index += 1 is happening before you ever do statusDiv.innerHTML = zeroArray[index]; so it's 1 (not 0) the first time you get there...

Try moving the index assignment operator to the end of your method here. As it is, you are FIRST increment the index, then doing work, meaning you are skipping the 0 frame...

Sometimes I ask myself why I help. If you just want to loop over those images it's like:
function loopImages(elem, imgs, interval, loop){
var i = 0, loopy = setInterval(function(){
elem.src = imgs[i++];
if(i === imgs.length){
loop ? i = 0 : clearInterval(loopy);
}
}, interval);
}
loopImages(document.getElementById('zeroImage'), zeroArray, 700, true); // loops forever

Related

How to delay two functions inside a loop?

I've been searching all day and I can't figure out how to fix it.
All I wanna do is iterate through a bunch of elements and do the following things to each of it:
Add a class
Wait 3s
Remove the class added
Go to the next element
I've tried many things and now I have this:
/* Avatars is an array of elements */
var i = 0
function testimonialCarousel(avatars){
const avatarsLen = avatars.length
avatars[i].classList.add("focused-avatar");
i++;
if (i > 0){
avatars[i-1].classList.remove("focused-avatar");
};
if (i < avatarsLen) {
setTimeout(testimonialCarousel.bind({}, avatars), 3000);
} else{
i = 0;
};
};
I know that there are many questions here already covering the delay of a single function, for example: How do I add a delay in a JavaScript loop?
This is not my case. I can achieve it, adding the class for each element with a 3s interval. What I'm not able to achieve is the "remove class" step.
Does anybody may help me?
Ok, I've found out how to handle it:
for (let i = 0; i <= avatarsLen; i++){
setTimeout(function(){
if (i > 0){
avatars[i-1].classList.remove("focused-avatar");
};
if (i == avatarsLen) {
return testimonialCarousel();
};
avatars[i].classList.add("focused-avatar");
balloonMessage.style.opacity = 0;
balloonName.style.opacity = 0;
setTimeout(function(){
balloonMessage.innerHTML = balloonContent[i].message;
balloonName.innerHTML = "— " + balloonContent[i].name;
balloonMessage.style.opacity = 1;
balloonName.style.opacity = 1;
}, 650)
}, i*3000); /* <--- The solution lays here. */

Loop to check last image in array

Thanks to a kind member I found a solution to a code problem of mine!
But I'm having struggle again with a loop.. I tried to find the solution in answered questions but nothing was working for me..
I want a loop to check if the last image in an array is loaded. I'm making a simple game where you click on a image, and it changes to the next image. The goal is that you have to click multiple times on the image, to get to the last image. If you are at the last image, you win. There needs to be a timer that checks after let's say 5 seconds, if you are at the last image. (I have multiple images that you have to click on, bet I'm showing just one right now)
So I made a for loop like this:
for (eiImg == 'img/ei4.png'){
alert("yay!");
}
It's probably very very wrong but I'm a very amateur programmer so I'm sorry! ;)
Well of course it wasn't working. And I am not even using a timer..
Can someone teach me how to successfully make a loop that checks after 5 seconds if the Image is the last image in the array. I've tried to google it but I just can't find the solution.
Here is my entire javascript code:
var eieren = 0;
var eieren = Math.floor((Math.random() * 4) + 1);
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
imgArray.length;
var eiImg = imgArray[eieren - 1];
console.log( eiImg );
// thanks so much for the help Azzy Elvul!
document.getElementsByTagName( 'img' )[0].src = eiImg;
document.getElementsByTagName( 'img' )[0].addEventListener( "click", changeImage ());
var counter = eieren - 1;
function changeImage()
{
//Load new image if this is not the last image
if ( counter < imgArray.length - 1 )
{
document.getElementsByTagName( 'img' )[0].src = imgArray[ ++counter % imgArray.length];
}
};
Check this, its create alert of the last object from the array
var imgArray = [ 'img/ei1.png' , 'img/ei2.png' , 'img/ei3.png', 'img/ei4.png' ];
var alertIndex = imgArray.length-1; // the last index from the array
for(var i = 0; i<imgArray.length; i++) {
if(i == alertIndex) {
alert(imgArray[i]);
}
}
JSFiddle - look at this working example.
OK, so I was curious about this and about the solution you were working on and so I had a go at it myself just to see if I could get it to work. I think my solution is slightly different from your approach. The annotated code is below and there's a JSFiddle demonstration of the code at the end.
var imgArray = ['img/ei1.png', 'img/ei2.png', 'img/ei3.png', 'img/ei4.png'];
// get the body element and create an array to keep the image elements
var body = document.querySelector('body');
var imgs = [];
// loop over the list of images, creating new elements
// adding src attributes and click events to them, and then adding
// them to the imgs array we created
for (var i = 0, l = imgArray.length; i < l; i++) {
var img = document.createElement('img');
img.src = imgArray[i];
img.addEventListener('click', changeImage);
imgs.push(img);
}
function changeImage() {
// are there any image elements left in the img array
// if there are, continue
if (imgs.length > 0) {
// is the length of the img array less than the length
// of the imgArray - if so, remove the previous image from the page
if (imgArray.length !== imgs.length) {
body.removeChild(document.querySelector('img'));
}
// random number based on the number of image elements
// remaining in the imgs array
var random = Math.floor((Math.random() * imgs.length - 1) + 1);
// add that image to the body element
body.appendChild(imgs[random]);
// remove the image element from the imgs array
imgs.splice(random, 1);
}
}
function checkOnLastImage() {
// are you on the last image?
if (imgs.length === 0) {
console.log('congratulations')
} else {
console.log('try again');
}
}
// run changeImage for the first time
changeImage();
// use a setTimeout to check at 5 seconds whether
// the last image has been reached
setTimeout(checkOnLastImage, 5000);
DEMO
Why to iterate? Get the last object directly.
alert(arr[arr.length-1])

Javascript Image slideshow doesn't work

I'm trying to get one image from this array to display every two seconds using Javascript, but I can't seem to get it to work. The id is correct and the image locations are correct and all spelt right. Not sure what's going wrong, any help would be greatly appreciated! Thanks in advance!
var images = new Array();
images[0] = "images/slideshowimage1.jpg";
images[1] = "images/slideshowimage2.jpg";
images[2] = "images/slideshowimage3.jpg";
images[3] = "images/slideshowimage4.jpg";
var counter = 0;
function ChangePic()
{
counter++;
document.getElementById('carpic').src = images[counter];
if(counter == images.length)
{
counter = 0;
}
setTimeout("ChangePic()",2000)
}
Well, first off you need to wrap the call in the setTimeout in a function, not a string.
Second, the counter never reaches the value 0 because you increase it's value by 1 from the start. You want to do something like this:
var images = new Array();
images[0] = "images/slideshowimage1.jpg";
images[1] = "images/slideshowimage2.jpg";
images[2] = "images/slideshowimage3.jpg";
images[3] = "images/slideshowimage4.jpg";
var counter = 0;
function ChangePic()
{
document.getElementById('carpic').src = images[counter];
// a more efficient if/else statement can be written like this:
// don't forget that the array starts with 0, so you need array length -1
(counter == images.length-1) ? counter = 0 : counter++;
}
// need to move this out of the ChangePic function
setTimeout(function() {ChangePic()}, 2000);
You should remove the double quotes and braces in the setTimeout function.
It should be:
setTimeout(ChangePic, 2000);
Hm, I think there are a couple of problems here. First is a syntax error, then a logic error.
The syntax error is your argument for setTimeout. It should be setTimeout(ChangePic, 2000), rather than setTimeout("ChangePic()", 2000).
The logic error is in the position of your increment, counter++ - in its present position, the values that will end up being used as an index for the array images[] will be 1, 2, and 3. Index 0 (the first item in images[]) will never be used, since counter always gets incremented before it is used as an index (making it impossible for it to be 0 when it is used). What you'll want to do is move counter++ after you use it as an index for images[].
Adjusting your code as little as possible, here's what it might look like:
var images = new Array();
images[0] = "images/slideshowimage1.jpg";
images[1] = "images/slideshowimage2.jpg";
images[2] = "images/slideshowimage3.jpg";
images[3] = "images/slideshowimage4.jpg";
var counter = 0;
function ChangePic() {
document.getElementById('carpic').src = images[counter];
counter++;
if (counter == images.length) {
counter = 0;
}
setTimeout(ChangePic, 2000)
}
// Call function at end to begin slideshow cycle
ChangePic();
Here's a JSFiddle to show you what this does. (Open your browser's debug console to view the output.) Hope this is what you were looking for! If not, let me know and I'll be happy to help further.

For Loop/Each Loop variable storage and comparison (jQuery or Javascript

I have an each loop with jquery (I wouldn't mind using a for loop if the code works better) and it's cycling through all divs with the class="searchMe". I would like to store the current div in a variable that I can use in the next iteration of the loop to compare a value with the new current div. Some code is removed (all working) to simplify things, but here's my code:
$('.searchMe').each(function(){
var id = $(this);
sortUp += 1,
sortDown -= 1;
if (test) {
id.attr("name", ""+sortUp+"");
}
else {
id.attr("name", ""+sortDown+"");
}
if ( id.attr("name") > lastId.attr("name") ) {
id.insertBefore(lastId);
}
lastId = id; //this doesn't work, but illustrates what I'm trying to do
});
Everything is working properly except the last 3 lines.
is this possible with an each/for loop?
I don't know why sort up is needed when you are comparing backwards alone. you can replace the last three lines with...
if ( parseInt(id.attr("name")) > parseInt(id.prev().attr("name")) ) {
id.insertBefore(id.prev()).remove();
}
you can use index in $.each()
like
$('.searchMe').each(function(index){
var id = $(this);
sortUp += 1,
sortDown -= 1;
if (test) {// don't know what is test, let it is predefined
id.attr("name", sortUp);// no need to add ""
}
else {
id.attr("name", sortDown);
}
if ($('.searchMe').eq(index-1).length && id.attr("name") > $('.searchMe').eq(index-1).attr("name") ) {
id.insertBefore($('.searchMe').eq(index-1));
}
});
Or Alternatively you can define lastid like
var lastId='';// let it be global
$('.searchMe').each(function(index){
var id = $(this);
sortUp += 1,
sortDown -= 1;
if (test) {// don't know what is test, let it is predefined
id.attr("name", sortUp);// no need to add ""
}
else {
id.attr("name", sortDown);
}
if (id.attr("name") > lastId.attr("name") ) {
id.insertBefore(lastId);
}
lastId=id;// assign here the current id
});
Read eq() and $.each()

Adding increased count to the DOM for every pass

what I'm hoping to achieve is to increase a count and then append that to the DOM on every pass through using each(). What I have at the moment is the final count added at the end. For example.
Say I have 100 divs, for every pass through it should add the new count as it counts it, like so 1,2,3,4,5,6,7... and so on. But at the moment it counts all the objects and just appends 100 at the end. Please can someone point me in the direction to where I'm going wrong?
I've added a very basic version of what I'm hoping to achieve below... also here is a JSbin (I tried jsfiddle but it seems to be down for me) .
$(".toCount").each(function(i){
$("#count").text(i + 1);
});
$('input').on('click',function () {
var len = $(".toCount").length;
var arr = [];
for (var i = 0; i < len; i++ ) {
arr.push(i+1);
}
$('#count').text(arr.join());
});
I don't know what you mean by 1, 2, 3 ... in case that you want to count the elements step by step you can use setInterval function:
$('input').on('click',function () {
var l = $(".toCount").length,
$c = $('#count'),
i = 0;
var t = setInterval(function() {
i++;
$c.text(i);
if (i === l) clearInterval(t);
}, 10);
});
http://jsbin.com/eronel/17/edit
use append();
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
in your case text() is replacing your div's text so u get 100 at the end ..
$("#count").append(i + 1);
Use append
$("#count").append(i + 1);

Categories

Resources