Javascript image slideshow using a for loop - javascript

i'm trying to cycle through 3 images using a for loop in javascript. Here is my code:
<img name="slide" width="300" height="300">
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
window.onload = changeImage;
Currently, only image 3 is displayed. Anyone know what i'm doing wrong here?

Yes - this is because your for loop run finishes instantly so there's no time for slides 1 and 2 to be shown.
Give this a try:
var currentImage = 0,
images = [
"https://unsplash.it/200/300?image=100",
"https://unsplash.it/200/300?image=101",
"https://unsplash.it/200/300?image=102"
];
function initSlideshow() {
setImage(0);
setInterval(function(){
nextImage();
},1000);
}
function nextImage() {
if(images.length === currentImage + 1){
currentImage = 0;
} else {
currentImage++;
}
setImage(currentImage);
}
function setImage(image) {
document.querySelectorAll('.slide')[0].src = images[image];
}
window.onload = initSlideshow();
Example: https://jsfiddle.net/vvbdwazc/

Currently, only image 3 is displayed. Anyone know what i'm doing wrong
here?
it's all being displayed but the reason why you can only see the 3rd image is because you're not pausing for a certain time before displaying the next image hence it seems like it's not working.
use setInterval() method to show each image after a specified time.
Example:
var i=0;
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
function changeImage () {
for(i=0; i < images.length; i++) {
document.slide.src = images[i];
}
}
var myVar = setInterval(function(){ changeImage() }, 1000);
You may later wish to prevent the setInterval() method from executing any longer in that case have a look at clearInterval().

window.onload = changeImage; tells me you want to change the image on page load event? In other words, the image changes only upon page load (or refresh).
Since state is not maintained by default (eg local storage or session storage or cookies) your best bet would be to use a random generator to choose randomly. See Generating random whole numbers in JavaScript in a specific range?

This is because the for works so fast it gets quickly to the third image. You could use instead some setInterval like this:
<img id="slide" width="300" height="300">
<script>
var images = [];
images[0] = "images/1.jpg";
images[1] = "images/2.jpg";
images[2] = "images/3.jpg";
var i = 0;
setInterval(function() {
var slide = document.querySelector("#slide"); //Select the img element by ID
slide.src = images[i++];
if(i > images.length - 1)
i = 0;
}, 1000); //Time in milliseconds
</script>
This will change constantly back to the first image when it reaches the last one.
Edit: Forgot to mention. setInterval works like a "repeater", it will work indefinitely until you clear it. To clear it you need to asign it to a variable and then use clearInterval passing the variable.
var interval = setInterval(function(){}, 1000) //example
clearInterval(interval);
Like so.

Related

Manual traffic light conversion into automatic via Javascript

I am trying to do a traffic light sequence which runs on a timed basis automatically without user input . I have now got the code working but it only runs through once and then stops so how can I change this so it keeps going? Here is my code:
<!DOCTYPE html>
<html>
<head>
<script>
var images = new Array()
images[0] = "image2.jpg";
images[1] = "image3.jpg";
images[2] = "image4.jpg";
setInterval("changeImage()", 3000);
var x=0;
function changeImage()
{
document.getElementById("img").src=images[x]
x++;
}
</script>
</head>
<body>
<img id="img" src="image1.jpg">
</body>
</html>
To make this automatic, you can either put it in a loop, or you can use the setInterval function.
var interval = setInterval(nextLightClick, 1500);
This will loop indefinitely, running the function every 1500 milliseconds (1.5 seconds). If you want to stop it, you can simply say:
clearInterval(interval);
Here's an example -- note that I am changing the innerHTML, rather than the src, and I am using a div instead of image, but the logic will be exactly the same.
var tlight = new Array("1green.jpg","2yellow.jpg","3red.jpg");
var index = 0;
var tlightLen = tlight.length;
var image = document.getElementById('firstlight');
image.innerHTML = tlight[index];
var interval;
function startInterval() {
interval = setInterval(nextLightClick, 1500);
}
function stopInterval() {
clearInterval(interval);
}
function nextLightClick() {
index++;
if (index == tlightLen)
index = 0;
image.innerHTML = tlight[index];
}
<span id="firstlight"></span></br>
<button onclick="startInterval()">Start</button>
<button onclick="stopInterval()">Stop</button>

Javascript image slider setInterval()

I am making a simple image slider that runs through a directory containing images. The images is called "img_1", "img_2" and "img_3", so the point is to just iterate through them. The thing I don't get is how to implement a interval though. I want the images appear for 3 seconds, then change. The function "imgSlider" is on body load.
Edit: I am looking for simple solutions (in pure JS) as I am currently learning JS. Sorry for not clarifying it in the question. Lots of good answers here though!
function changeImg(img, i){
img.setAttribute("src", "img/slider/img_" + i + ".jpg");
}
function imgSlider(){
var img = document.createElement("img");
var targetDiv = document.getElementById("slider");
img.setAttribute("width", "100%");
img.setAttribute("height", "70%");
targetDiv.appendChild(img);
for(i=1; i<4; i++){
setInterval(changeImg(img, i), 3000);
}
}
What you need to do is simple, you have to change the setInterval code like this:
$(function () {
var curImg = 1;
setInterval(function () {
$("img").attr("src", "//placehold.it/100?text=" + ++curImg);
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="//placehold.it/100?text=1" />
Here, I have given an interval of 2 seconds for checking. I have used jQuery only for the updating of image. If you want it in plain JavaScript, it is possible through your code.
Pure JS Version
var curImg = 1;
setInterval(function () {
document.getElementsByTagName("img")[0].src = "//placehold.it/100?text=" + ++curImg;
}, 2000);
<img src="//placehold.it/100?text=1" />
You can do it this way.
Initialize a counter, that will keep a track of current image to being displayed. Now all we need to is call showImage function that will show the image corresponding to the current value of the counter.
Repeat this every 3sec.
var count = 0;
setInterval( function() {
showImage(count);
count = (count+1)%total_no_of_images
}, 3000)
setInterval takes a function, you need to pass it a reference to a function that it will run at the appropriate interval.
Also, note that as of this writing, the accepted answer assumes there are infinite images and has an "infinite loop" style of interval, which should be avoided if at all possible. Here, I stop the clock after the fifth image.
const changeImg = (img, i) => {
img.setAttribute('src', `img/slider/img_${i}.jpg`);
};
const imgSlider = () => {
const img = document.createElement('img');
const targetDiv = document.getElementById('slider');
img.setAttribute('width', '100%');
img.setAttribute('height', '70%');
targetDiv.appendChild(img);
let i = 0;
const interval = setInterval(
() => {
changeImg(img, i);
i += 1;
if (i > 4) {
clearInterval(interval);
}
},
3000
);
};

javascript setInterval / onload

I'm referring to the accepted answer for Change image in HTML page every few seconds. In this code, the very first timer event/image change occurs 6 secs after loading (then every 3 secs as expected). Could anyone explain to a beginner like me why this is so?
Thanks.
EDIT: Sorry for that, my fault. Let me try to explain what I'd like to do in the first place. The code given shows first startpicture.jpg and then cycles through image1.jpg to image3.jpg. I just want it to cycle through image1.jpg to image3.jpg without a seperate start picture (or all 4 pictures, including startpicture.jpg). Therefore is replaced startpicture.jpg with image1.jpg which made me get the wrong impression that the first image change occurred after 6 secs.
Maybe someone can help me how to change this code to cycling through the pictures without a designated start picture.
As per your edit, you can simply remove the startpicture (or replace with image1), and initially call the displayNextImage function immediately, then start the interval:
<!DOCTYPE html>
<html>
<head>
<title>change picture</title>
<script type = "text/javascript">
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("img").src = images[x];
}
function displayPreviousImage() {
x = (x <= 0) ? images.length - 1 : x - 1;
document.getElementById("img").src = images[x];
}
function startTimer() {
//call immediately
displayNextImage();
//then start interval
setInterval(displayNextImage, 3000);
}
var images = [], x = -1;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
</script>
</head>
<body onload = "startTimer()">
<img id="img" src="image1.jpg">
<button onclick="displayPreviousImage()">Previous</button>
<button onclick="displayNextImage()">Next</button>
</body>
</html>
may be its time taken to load the images ,
you can load all the image first and then start changing,
var images= new Array();
for(var i=0;i<imagelocation.length;i++)
{
images[i]=new Image();
images[i].onload=function(){ if(i=imagelocation.length){changeImage();}}
images[i].src=imagelocation[i]; //image location is array containg link
}
function changeImage()
{
//what u had written earlier
}

How to get JavaScript to rotate through a series if images

I'm having an issues where I cannot get my code to rotate multiple images in a cycle for my image gallery (just a bunch of images i got on google). I can however to get 1 image to cycle through the images but everything iv tried to get it to work with more than one has failed. Any help/ tips would be useful. Im in college for web development and i understand the basics of javascript it just seems when it comes to creating applications i have a bit of trouble.
Here is a link to my code: jsFiddle
$(document).ready(function () {
var img = document.images;
// Holds the image collection
var counter = 0;
var imgArray = [];
imgArray[0] = "http://www.zeroprox.tk/temp/images/img1.png";
imgArray[1] = "http://www.zeroprox.tk/temp/images/img2.jpg";
imgArray[2] = "http://www.zeroprox.tk/temp/images/img3.png";
imgArray[3] = "http://www.zeroprox.tk/temp/images/img4.jpg";
imgArray[4] = "http://www.zeroprox.tk/temp/images/img5.jpg";
imgArray[5] = "http://www.zeroprox.tk/temp/images/img6.png";
imgArray[6] = "http://www.zeroprox.tk/temp/images/img7.jpg";
imgArray[7] = "http://www.zeroprox.tk/temp/images/img8.png";
$("#left-arrow").click(function () {
if (counter < 0) {
counter = imgArray[counter] - 1;
} else {
counter--;
}
img[1].src = imgArray[counter];
});
// Left arrow... Previous
$("#right-arrow").click(function () {
counter = (counter + 1) % imgArray.length;
img[1].src = imgArray[counter];
});
// right arrow... Next
});
JSFiddle
Check this, it should solve your problem ;)
You were replacing every time the same image, now creates a new one and remove another.
Also added div#imagelist to use as a image container and access easier from JavaScript
var newImg = $(document.createElement("img"));
newImg.attr("src",imgArray[counter]);
$("#imagelist img").last().remove();
$("#imagelist").prepend(newImg);

Javascript timed slideshow not working in the least

And it's saddening. Some background, I'm new to Javascript and this is my first application of in life, and since plowing halfway through half a Javascript textbook in two days. It's an external file that's linked to at the end of my HTML. If any more is required, please ask and I'll do my best to provide.
var slide = document.getElementById("slide");
setInterval(slideshow.changeSrc, 5000);
var slideshow = {
changeSrc : function() {
if(slide.src === "./images/s1.png"){
slide.src = "./images/s2.png";
}
else if(slide.src === "./images/s2.png"){
slide.src = "./images/s3.png";
}
else{
slide.src = "./images/s1.png";
}
}
}
slide.addEventListener("load", slideshow.changeSrc, false);
The src property is the result of the browser resolving the URL you give it. Do not use it for comparisons. In addition, only the window and certain elements such as images or scripts have load events. Try this:
Instead, why not just keep track of an index?
(function() {
var id = 0, slide = document.getElementById('slide');
setInterval(function() {
id++;
slide.src = "images/s"+id+".png";
id %= 3;
},5000);
})();
I think this is what you are trying to achive:
var slide = document.getElementById("slide");
var slideshow = {
changeSrc : function() {
setTimeout(function() {
slide.src = 'http://lorempixel.com/100/100';
}, 1000);
}
}
slide.addEventListener("load", slideshow.changeSrc, false);
http://jsfiddle.net/Bs4gM/

Categories

Resources