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.
Related
I trying to make a small text based rpg game, but I came across array in js and then I came to problems, I failing to increase the index number by using i instead of 0 like myArray[i]
I made a jsfiddle so you guys can see what I mean.
jsfiddle
When you press the button til you get a warming, it should increase the i to 2, but it don't, but still comes with warming and increasing the attack variable.
This is your attackUp function:
function attackUp(){
var i = 0;
var attackCost = xpforlevel[i];
if (attackCost < attackxp) {
alert("WARMING!");
attack++;
document.getElementById('attack').innerHTML = attack;
i++;
document.getElementById('i').innerHTML = i;
}
}
Notice that your var i = 0 statement doesn't really make sense (because everytime attackUp is called, i will be reset to = 0 at the beginning). To fix that, erase this var i = 0 statement from your function and put in the beginning of your JS code:
var i = 0;
var attackxp = 0;
var attack = 1;
Further, your function will only update i if attackCost < attackxp, otherwise it will change nothing. You need to put the i++; statement outside your if-block, like this:
function attackUp(){
//erase this line: var i = 0;
var attackCost = xpforlevel[i];
i++; //added this line
if (attackCost < attackxp) {
alert("WARMING!");
attack++;
document.getElementById('attack').innerHTML = attack;
//erase this line: i++;
document.getElementById('i').innerHTML = i;
}
}
As your i is a local variable, it is initiated as 0 every time you call attackUp(). You should put it besides attackxp and attack.
For more information about the scope of variable in JavaScript, see w3schools or this question.
This is my code, I'm not sure whether I am using the correct loop but this is basically want to do. I am trying get every src in the array to print out every one second, but the myPix[thisPic] becomes undefined when attempting to print out the second item in the myPix Array. I'd really be happy to get some help. Thank you!
function nextPic() {
count = -1;
thisPic = 0;
if (thisPic == count) {
document.write("This shouldn't ever happen");
return false;
} else {
count++;
var myPix = new Array("images/slideshow/Jellyfish.jpg", "images/slideshow/Penguins.jpg", "images/slideshow/Lighthouse.jpg");
slideTag = document.getElementsByTagName("img")[1];
slideTag.src = myPix[thisPic];
currPic = slideTag.src;
document.write(myPix[thisPic] + "<br />");
document.write(currPic);
}
return false;
}
setInterval(nextPic, 1000);
Code doesn't work because "loop" has no shared variables. Every iteration should work on the same array and the same iterator, in Your code every iteration created new array and new iterator, so every iteration was doing the same thing.
To work correctly every loop iteration must:
Take current image src from array ( one variable declared outside loop )
Set it on img element
Change current variable to current+1 ( current variable delared outside loop )
If our current is more that array size then - end (clearInterval) or set current on 0 - then will start again and again ...
//array declaration should be outside of loop
var myPix = new Array("https://www.gravatar.com/avatar/50fbdd1dcbe4763a33a0e212f6a632c8?s=32&d=identicon&r=PG&f=1", "https://www.gravatar.com/avatar/5be6299fb284071a9fd2cc2cc0b9090a?s=32&d=identicon&r=PG", "https://i.stack.imgur.com/mlB9c.jpg?s=48&g=1");
var currentPic=0; //this is number of current picture
function nextPic(){
if (currentPic>= myPix.length){
// here example how to stop:
//clearInterval(interval);
//return;
//we loop it over again from begging
currentPic=0;
}
//get img in page - image by currentPic
slideTag = document.getElementsByTagName("img")[1];//second
//set src on this slideTag from array
slideTag.src = myPix[currentPic];
currentPic++;
}
var interval=setInterval (nextPic, 1000);//save interval in variable to use it to stop
<h1>images</h1>
<img><br/>
<img><br/>
<img><br/>
I taken example avatars from stackoverflow to show working example :)
As per understanding your code, I have figurout your issue
var myPix = ["images/slideshow/Jellyfish.jpg", "images/slideshow/Penguins.jpg", "images/slideshow/Lighthouse.jpg"];
counter=0;
interval = setInterval (nextPic, 1000);
function nextPic(){
if(counter >= myPix.length){
document.write("This shouldn't ever happen");
clearInterval(interval);
}
else{
slideTag = document.getElementsByTagName("img")[1];
slideTag.src = myPix[counter];
currPic = slideTag.src;
document.write(myPix[thisPic] + "<br />");
document.write(currPic);
counter++;
}
}
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])
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
The goal: When the page is loaded, display the image andy_black.jpg. After two seconds, change the image source, and the thus image in the browser, to a second image called andy_white.jpg. This will change back and forth every 2 seconds.
I checked out this article:
SetInterval function calls
(I searched other as well, with the tags [javascript] [function] and the word "setinterval", but most were using jQuery and my intention here is not to use any jQuery, it's an experiment in JavaScript after all).
which was quite helpful for before I had read it my code was much longer and the function was not called in the setInterval() function.
So here's some code:
Suggestions?
var i = 1;
function change_pic() {
i + 1;
if (i == 5) {
i = 1;
}
//I suspect the computer will read i as 5 for some
//tiny amount of time before reverting back to 1
//which I suspect could cause a further problem, but
//is it the source of the current issue?
if (i == 1 || i == 2) {
document.getElementById('img_to_flip').src = "https://cdns-images.dzcdn.net/images/artist/5d9e44027cc266260d7bd932d98f739d/500x500.jpg";
} else {
document.getElementById('img_to_flip').src = "https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg";
}
}
var pic_src = setInterval(change_pic, 2000);
<img id="img_to_flip" src="https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg" height="100" width="100" />
You forget to actually reassign the new value to i.
Either use:
i = i + 1;
or
++i;
Also, why count to five when you only have two states? A common paradigm to have an auto-resetting counter is to use modulo arithmetic:
i = (i + 1) % 2;
which guarantees that i will only ever have values of 0 or 1.
FWIW, here's an alternate way of writing the entire feature that'll work for any number of images - just populate the pics array:
(function() { // function expression closure to contain variables
var i = 0;
var pics = ["https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg", "https://cdns-images.dzcdn.net/images/artist/5d9e44027cc266260d7bd932d98f739d/500x500.jpg"];
var el = document.getElementById('img_to_flip'); // el doesn't change
function toggle() {
el.src = pics[i]; // set the image
i = (i + 1) % pics.length; // update the counter
}
setInterval(toggle, 2000);
})(); // invoke the function expression
<img id="img_to_flip" src="https://media.s-bol.com/q7R3B8QVrAj2/550x549.jpg" height="100" width="100" />
If you want to avoid the delay in first time setInterval call the function before the setInterval as shown in the top answer:
(function() { // function expression closure to contain variables
var i = 0;
var pics = [ "andy_white.jpg", "andy_black.jpg" ];
var el = document.getElementById('img_to_flip');
function toggle() {
el.src = pics[i]; // set the image
i = (i + 1) % pics.length; // update the counter
}
toggle()
setInterval(toggle, 2000);
})(); // invoke the function expression