My automatic image slider only shows the first two images - javascript

My automatic image slider only shows the first two images of the images array while tere are three images. I can't figure out why it is not working properly, I hope someone might know what is going wrong.
var images = [];
var i = 0;
//image array
images[0] = 'https://placeimg.com/900/600/animals?t=1515065784396';
images[1] = 'https://placeimg.com/900/600/animals?t=1515065867693';
images[2] = 'https://placeimg.com/900/600/animals?t=1515065784396';
function changeImage() {
"use strict";
document.getElementById("slider").src = images[i];
if (i < images.length - 1) {
i += 1;
} else {
i = 0;
}
setInterval(changeImage, 2000);
}
window.onload = changeImage;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Automatic Image Slider </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<img id="slider">
</body>
</html>

Here it is! I've modified your code so that it now will work, pay attention not to reinitialize the interval at every changeImage() call ;)
//image array
var images = [];
images[0] = 'https://placeimg.com/900/600/animals?t=1515065784396';
images[1] = 'https://placeimg.com/900/600/animals?t=1515065867693';
images[2] = 'https://placeimg.com/900/600/animals?t=1515065784397';
var i = -1;
function changeImage() {
"use strict";
++i;
if (i >= images.length) {
i = 0;
}
document.getElementById("slider").src = images[i];
}
setInterval(changeImage, 2000);
window.onload = changeImage;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> Automatic Image Slider </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<img id="slider">
</body>
</html>

images.length = 3
but
images.length - 1 = 2
so
(i < images.length - 1)
this condition work inly for i = 0 and i = 1
use this condition instead
(i < images.length)

Actually, your code works with a little bug. Note that your first and last image is the same.
And the huge bug of your code is that you are creating a new interval at each changeImage call, so the last image is being placed but fastly replaced for the first image.
Remove the setInterval(changeImage, 2000) from the changeImage function and call it like this:
window.onload = function() {
changeImage();
setInterval(changeImage, 2000)
}

Because your condition if (i < images.length - 1) is true only for 0 an 1
If you do if (i<=images.length-1) you will get all the three images

Related

Undifined error after switching through images in Javascript

I am trying to create a website with one picture in the middle that changes after a given time. However after running through the loop once, no picture is shown for a short while and my console shows:
Shortly after, it switches through the images again. But having the image dissapear for a short while is a no go.
My Javascript looks like this:
var allPictures = new Array();
var index = 0;
allPictures[0] = "imgA.jpg";
allPictures[1] = "imgB.jpg";
allPictures[2] = "imgC.jpg";
addEventListener("load",() => {
setInterval( function() {
changeImage()
}, 500);
});
function changeImage() {
document.getElementById("galleryPicture").src = allPictures[index];
if (index < allPictures.length) {
index += 1;
} else if (index >= allPictures.length) {
index = 0;
}
}
My HTML looks like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="main.css">
<title>Website</title>
</head>
<body>
<script src="pictureSwapScript.js"></script>
<div class="galleryPicture">
<img id= "galleryPicture" src="imgA.jpg">
</div>
</body>
</html>
The problem is the condition used to increment index, it will get outside the boundaries of the array.
Replace it with
if (index >= allPictures.length - 1) {
index = 0;
} else {
index += 1;
}
There are other minute improvements that can benefit your code, among which the most obvious to me is replacing:
setInterval( function() {
changeImage()
}, 500);
with just
setInterval(changeImage, 500);
Below code solves your usecase.
function changeImage() {
if (index < allPictures.length - 1) {
index += 1;
} else if (index >= allPictures.length - 1) {
index = 0;
}
document.getElementById("galleryPicture").src = allPictures[index];
}
You were trying to compare index value with length, index always starts from 0. Hence you will have to decrease length by 1 because length starts from 1

how to change image for every 4 seconds in javascript?

i want to change image i have done code still image is not showing at all. file not found error is showing i want to change image every 4 seconds how can i do that? please help
<html lang="en">
<head>
<title>sliding image</title>
</head>
<body onload="f1()">
<img id="img1" src=""alt="" width="200px">
<script>
let arr=new Array();
function image()
{
let img2=document.getElementById("img1");
x=0;
arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png"
img2.src=arr[x];
x=1;
arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg"
img2.src=arr[x];
x=2;
arr[x]="C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
img2.src=arr[x];
x=0;
}
function f1()
{
window.setInterval(image,4000);
}
</script>
</body>
</html>
The images have the names 1.jpg, 2.jpg and 3.jpg and are in the same folder with test.html and test.js file. U can switch the timeout in seconds.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="test.js" type="text/javascript" defer></script>
</head>
<body>
<img id="imageSwitcher" src="" alt="">
</body>
</html>
"use strict";
const imageArray = ["1.jpg", "2.jpg", "3.jpg"];
const imageSwitcher = document.getElementById("imageSwitcher");
let timeout = 4;
let i = 0;
setInterval(() => {
imageSwitcher.src=imageArray[i];
console.log(i);
i++;
if (i >= imageArray.length) {
i = 0;
}
}, timeout * 1000);
You have to increment the pointer and reset it like below code.
<script>
var pointer = 0;
var imageArray = [
"C:\Users\SUDARSHAN\Desktop\html_UI\images\1200px-Heart_corazon.svg.png",
"C:\Users\SUDARSHAN\Desktop\html_UI\images\alex-haney-AGqzy-Uj3s4-unsplash.jpg",
"C:\Users\SUDARSHAN\Desktop\html_UI\images\mitchell-luo-jz4ca36oJ_M-unsplash.jpg"
];
function image()
{
let img2 = document.getElementById("img1");
img2.src = imageArray[pointer];
pointer++;
// reset the pointer if hit the max
if (pointer == imageArray.length-1){
pointer = 0;
}
}
function f1()
{
window.setInterval(image,4000);
}
</script>

Slideshow transition - Javascript

I'm trying to do a slideshow gallery in Javascript, but it doesn't work... When I run this code, the src goes to veyron.jpg instantly, skipping the lamborghini.jpg.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="img" src="ferrari.jpg" />
<script>
img = document.getElementById("img");
images = new Array("ferrari.jpg","lamborghini.jpg","veyron.jpg");
end = images.length -1;
window.onload = setInterval(slide,1000);
function slide(){
for(i=0;i<=end;i++){
img.src = images[i];
}
}
</script>
</body>
</html>
why loop is exist here, you are casting all the images in all.
Do it with increment variable with start
<script>
var img = document.getElementById("img");
var images = new Array("ferrari.jpg","lamborghini.jpg","veyron.jpg");
var end = images.length -1;
var start = 0;
window.onload = setInterval(slide,1000);
function slide(){
img.src = images[start%end];
start++;
}
</script>
example fiddle

How to do a continual loop for my traffic light sequence javascript?

I am trying to do a traffic light sequence which runs on a timed basis automatically without user input. I have got the code working now, 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>
Apply the remainder assignment %= to the counter with the length of the array.
function changeImage() {
document.getElementById("img").src = images[x];
x++;
x %= images.length;
}

document.getElementById returns null for unknown reason

The code is for a slider to switch images. When I run the page I get this error:
Cannot set property 'onclick' of null.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Slider</title>
<link rel="stylesheet" type="text/css" href="sliderswag.css">
<script language="javascript" type="text/javascript" src="imgslidescript.js"></script>
</head>
<body>
<div id="box">
<img id="main" src="http://lmetar.com/oscar1.jpg">
<img id="left" src="http://lmetar.com/left.png">
<img id="right" src="http://lmetar.com/right.png">
</div>
JavaScript:
document.getElementById('left').onclick = slideChange;
document.getElementById('right').onclick = slideChange;
var slideNumber = 0;
function slideChange()
{
slideNumber += 1;
if (slideNumber > 3)
{
slideNumber = 1;
}
else
{
document.getElementById('main').src = 'http://lmetar.com/oscar' + slideNumber + '.jpg';
}
}
Move your script to the end of your page. You're running JavaScript on elements that don't yet exist.
Or wrap the code you have in a window.onload call which will execute the code after the window has loaded. Ex:
window.onload = function () {
document.getElementById('left').onclick = slideChange;
document.getElementById('right').onclick = slideChange;
var slideNumber = 0;
function slideChange() {
slideNumber += 1;
if (slideNumber > 3) {
slideNumber = 1;
} else {
document.getElementById('main').src = 'http://lmetar.com/oscar' + slideNumber + '.jpg';
}
}
};
Your JavaScript is loading before you content, therefore it is trying to find elements that do not exists. You have 2 options:
Move your <script> tag to the end of your page
Use the following to wait until the page has loaded before you execute your script
Code:
document.addEventListener("DOMContentLoaded", function(event) {
// Your Code Here
});

Categories

Resources