issues with slide show in JavaScript - javascript

I have this issues where the images can't display or javascript code is not working
The console show this
Uncaught ReferenceError: settimeout is not defined
at changeimage (carousel2.html:22)
The output is hello
var i = 0;
var images = [];
var time = 4000;
images[0] = 'images/cake.jpg';
images[1] = 'images/cake1.jpg';
images[2] = 'images/cake2.jpg';
images[3] = 'images/cake3.jpg';
images[4] = 'images/cake4.jpg';
function changeimage() {
document.src = images[1];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
settimeout("changeimage()", time);
}
window.onload = changeimage;
<title>carouse slide button</title>
<P>hello</P>

Issues in your code
Misspelled setTimeout
missing image tag
using images[1] over and over
You want to study this
const time = 4000;
const images = [
"https://picsum.photos/id/231/200/300",
"https://picsum.photos/id/232/200/300",
"https://picsum.photos/id/233/200/300",
"https://picsum.photos/id/234/200/300",
"https://picsum.photos/id/235/200/300"
];
let cnt = 0;
const changeImage = function() {
document.getElementById("img1").src = images[cnt];
cnt++;
if (cnt >= images.length) cnt = 0;
};
window.addEventListener("load", function() { // when the page loads
setInterval(changeImage, time); // call every 4 seconds
changeImage(); // but call it now too so we do not have to wait
});
<img id="img1" />

The function settimeout is not correctly written. Should be:
setTimeout(changeimage, time);
For more info, you can check this link.

Related

How do I use a variable to determine a display source in JavaScript?

I just started JavaScript and I can't figure out how to make an image change depending on a changing variable (I'd like to use relative file location). I watched a tutorial but the image replaces the tab instead of being part of it.
Here is my current progress:
<div class="Box">
//Irrelevant sibling div
<img name="slide" class="slide" />
</div>
<script>
var i = 0;
var images = [];
var time = 3000;
//Below is where I think the problem is
images[0] = window.location = "./Images/img1.jpg";
images[1] = window.location = "./Images/img2.jpg";
images[2] = window.location = "./Images/img3.jpg";
images[3] = window.location = "./Images/img4.jpg";
images[4] = window.location = "./Images/img5.jpg";
//Above is where I think the problem is
function changeImg() {
document.slide.src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout(changeImg, time);
}
window.onload = changeImg;
</script>
I've tried using window.location.href but it had an identical result as what I currently have.
You definitely don't want to set the window location to the image itself. Just remove that:
images[0] = "./Images/img1.jpg";
images[1] = "./Images/img2.jpg";
images[2] = "./Images/img3.jpg";
images[3] = "./Images/img4.jpg";
images[4] = "./Images/img5.jpg";
You could also simplify your code a little:
var i = 0;
var images = [];
var time = 3000;
function changeImg() {
document.slide.src = `./Images/img${++i}.jpg`;
i = i % 5;
setTimeout(changeImg, time);
}
window.onload = changeImg;
to start with, I will assume that you have an image tag with slide as ID like
<image id="slide"></image>
form your code, I don't understand what do you want to do with the double equality on
images[0] = window.location = "./Images/img1.jpg";
images[1] = window.location = "./Images/img2.jpg";
images[2] = window.location = "./Images/img3.jpg";
images[3] = window.location = "./Images/img4.jpg";
images[4] = window.location = "./Images/img5.jpg";
remember that window.location is an object and that will jump to that location (it's a page reload) and upon reloading, it will no longer run the script
I would change to simple
images[0] = "./Images/img1.jpg";
images[1] = "./Images/img2.jpg";
images[2] = "./Images/img3.jpg";
images[3] = "./Images/img4.jpg";
images[4] = "./Images/img5.jpg";
now, the only place you need a small change, as the way HTML nodes work with javascript is the line where you call document.slide.src = images[i];
it should be
document.getElementById("slide").src = images[i];
and you will see all will work as expected
there's a bit more to your example you could make it better/refactor, but from your question, this are the 2 main changes :)
here's a simple example based on your code
var i = 0;
var images = [];
var time = 3000;
//Below is where I think the problem is
images[0] = "https://via.placeholder.com/150?text=image 1";
images[1] = "https://via.placeholder.com/150?text=image 2";
images[2] = "https://via.placeholder.com/150?text=image 3";
images[3] = "https://via.placeholder.com/150?text=image 4";
images[4] = "https://via.placeholder.com/150?text=image 5";
//Above is where I think the problem is
function changeImg() {
document.getElementById("slide").src = images[i];
if (i < images.length - 1) {
i++;
} else {
i = 0;
}
setTimeout(changeImg, time);
}
window.onload = changeImg;
<image id="slide"></image>

Background image changer interval Javascript

I'm new to javascript and I need some help with a function that I am trying to get to run. I would like for the background of my body to change every seconds using the images provided but when I try to run the script it does not seem to work.
Javascript:
var i = 0;
var images = [
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010216.jpg'),
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010217.jpg'),
URL('file:///Users/BodyDesigns/Documents/Altered%20Images/P1010200.jpg')
];
function backgroundChanger() {
for(; i < images.length; i++) {
document.getElementById('background').style.backgroundImage.innerHTML = images[i];
}
}
setInterval( backgroundChanger(), 4000);
html:
<body id="background" onLoad="backgroundChanger()">
This should do the trick.
var i = 0;
var images = [
'https://upload.wikimedia.org/wikipedia/commons/2/23/Screenshot_from_IMAX%C2%AE_3D_movie_Hidden_Universe_showing_the_Helix_Nebula_in_infrared.jpg',
'http://ichef.bbci.co.uk/wwfeatures/wm/live/1280_640/images/live/p0/40/m0/p040m0bc.jpg',
'http://az616578.vo.msecnd.net/files/2016/08/06/636060577940287734-194579614_maxresdefault.jpg'
];
function backgroundChanger() {
if(i >= images.length){
i = 0;
}
document.getElementById('background').style.backgroundImage = 'url(' + images[i++] + ')';
}
setInterval( backgroundChanger, 4000);
As you can see, the url() should be passed inside a string to work. And there is no innerHtml on backgroundImage property.

How do you use increments?

I am not sure how to use increments.
through a function. i can't get the paragraph to show the array words
<p id= "demo"
var Array = ["hello", "goodbye"];
var mimg = document.getElementById(imageArray[0]);
mimg.setAttribute('src', [index]);
//var ArrayIndex = 0;
function change() {
("src", Array[Index]);
imageIndex++;
if (Index >= Array.length) {
Index = 0;
}
}
Don't forget to use your browser's console, read this article Using Your Browser to Diagnose JavaScript Errors.
Don't use setattribute function, use src attribute.
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
myImage.src = imageArray[0];
var imageIndex = 0;
function changeImage() {
myImage.src = imageArray[imageIndex];
imageIndex++;
if (imageIndex >= imageArray.length)
imageIndex = 0;
}
window.onload = function() {
setInterval(function() {
changeImage();
}, 1000);
};
<img id="mainImage" />
var myImage = document.getElementById("mainImage");
var imageArray = ["images/1.png","images/2.png","images/3.png","images/4.png"];
var mimg=document.getElementById(imageArray[0]);
mimg.setAttribute('src',photos[index]);
You aren't showing your relevant HTML, but I notice in this section you are getting an element with ID "images/1.png" and setting the src of that element to the value of something in photos[index]. You haven't shown how the photos array is loaded. Do you actually have an element with an ID "images/1.png"?
In your function, you set the src of the mainImage to the values in imageArray rather than the values in the photo array. That may be valid, but since that is different than what you did outside the function, I want to make sure that was intended.
I think you are talking about such solution:
var imageArr=["images/1.png", "images/2.png", "images/3.png", "images/4.png"];
$('#button'). on('click',function(){
var index=(Math.random(0,imageArr.length)*10)
$('#img').attr('src',imageArr[index])
});
Again you question is not clear, thus I think this will help you to get direction.
This should be solution if you are using plain JavaScript
var myImage = document.getElementById("mainImage"),
imageArray = ["images/1.png", "images/2.png", "images/3.png", "images/4.png"],
imageArrayIndex = 0;
myImage.src = imageArray[imageArrayIndex++];
function changeImage () {
myImage.src = imageArray[imageArrayIndex++];
imageArrayIndex = imageArrayIndex >= imageArray.length ? 0 : imageArrayIndex;
}
Make sure that your element is defined as "img".
Here's a solution which sets a data-index attribute on the image to keep track of the selected index. This solution is compatible with down to IE8 and does not use the Jquery library. Run the code snippet below for a test (click the image to go to the next one).
var mimg = document.getElementById('main-image'),
simg = document.getElementById('sec-image')
imgArr = [
'http://placehold.it/50x50/00AAAA',
'http://placehold.it/50x50/AAAA00',
'http://placehold.it/50x50/AA00AA',
];
var loopImages = function(element, imgArray, startAt) {
var index = element.getAttribute('data-index'),
newIndex = 0;
if (!index)
newIndex = ((startAt && startAt < imgArr.length-1) || 0) + 1;
else if (index < imgArr.length-1)
newIndex = parseInt(index) + 1;
element.setAttribute('data-index', newIndex);
element.src = imgArr[newIndex];
};
mimg.addEventListener('click', function(e) {
loopImages(e.target || e.srcElement, imgArr);
});
setInterval(function() {
loopImages(simg, imgArr);
}, 500);
<p>Preview (click to change)</p>
<img id="main-image" src="http://placehold.it/50x50/00AAAA">
<br>
<p>Preview with interval</p>
<img id="sec-image" src="http://placehold.it/50x50/00AAAA">

How can I make my javascript slider more responsive (faster)?

This is my first project in Javascript. It's an image slider with a next and previous arrow. One thing really bothering me is that there can some very noticeable lag between clicking an arrow and the image actually changing.
I'd really appreciate if someone review my code and let me know what I could do better.
http://jsfiddle.net/afptfbs8/40/
var myImage = document.getElementById("mainImage");
var imageArray = ["http://lorempixel.com/400/200/sports/1/", "http://lorempixel.com/400/200/sports/2/", "http://lorempixel.com/400/200/sports/3/", "http://lorempixel.com/400/200/sports/4/"];
var imageIndex = 0;
var prevImage = document.getElementById("prev");
var nextImage = document.getElementById("next");
var myTime = 3000;
var myInterval = setInterval(changeImage, myTime);
function changeImage() {
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
myImage.setAttribute("src", imageArray[imageIndex]);
}
prevImage.onclick = function() {
clearInterval(myInterval);
myInterval = setInterval(changeImage, myTime);
if (imageIndex === 0) {
imageIndex = imageArray.length -1;
} else {
imageIndex = imageIndex - 1;
}
myImage.setAttribute("src", imageArray[imageIndex]);
};
nextImage.onclick = function() {
clearInterval(myInterval);
myInterval = setInterval(changeImage, myTime);
if (imageIndex === imageArray.length -1) {
imageIndex = 0;
} else {
imageIndex = imageIndex + 1;
}
myImage.setAttribute("src", imageArray[imageIndex]);
};
imageArray.forEach(function (value, index) {
var node = document.createElement("li");
var textNode = document.createTextNode(index);
node.appendChild(textNode);
document.getElementById("myList").appendChild(node);
});
myInterval
The problem is that each time you change the picture, you are refetching it from the server. Take a look at the network panel to see. I suggest preloading all of the images so that they do not need to be refetched every time.
var images = new Array();
for (var i = 0; i < imageArray.length; i++) {
images[i] = new Image();
images[i].src = imageArray[i];
}

Without using jquery, how to cycle through images to make a simple slideshow

You have a div, with 3 images in it.
How to create a simple slideshow that cycles through the images, and displays each image for 5 seconds and goes back to the first image when done and continues looping.
Without using jquery or any other framework.
(function () {
var imgs = document.getElementById('your_div').getElementsByTagName('img'),
index = 0;
imgs[0].style.display = 'block';
setInterval(function () {
imgs[index].style.display = 'none';
index = (index + 1) % imgs.length;
imgs[index].style.display = 'block';
}, 5000);
}());
Example HTML: http://jsfiddle.net/Zq7KB/1/
Edit: Saw a more elegant example above that used .length.
You can use setInterval to set up the timed callback, and set the src of an img element:
window.onload = function() {
var slides = [ "path_to_image_one",
"path_to_image_two",
"path_to_image_three" // ...
],
index = 0,
timer = 0;
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
...where your markup for the image is:
<img id="theImage" src="path_to_initial_placeholder">
Note that I've stored the timer handle in timer but not used it. This is just because you might use it to cancel the timer if you need to stop the slideshow.
Update: Just saw that you want to get the images from a div somewhere (whereas above I've supplied the paths in the code itself). Simple enough to create slides dynamically; revised edition of the above that grabs the images that are direct children of the div with the ID "theDiv":
window.onload = function() {
var slides = [],
index = 0,
timer = 0,
node;
// Get the slides
for (node = document.getElementById('theDiv').childNodes;
node;
node = node.nextSibling) {
if (node.nodeType == 1 && node.tagName == "IMG") {
slides.push(node.src);
}
}
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
Well you'd have to get a handle for the <div> first, so if it has an "id" value:
var theDiv = document.getElementById("imgContainer");
Now you just have to set up a timer to cycle through the images:
(function(div, sleep) {
var idx = 0;
var imgs = div.getElementsByTagName('img');
function showOne() {
for (var i = 0; i < imgs.length; ++i)
imgs[i].style.display = 'none';
imgs[idx].style.display = '';
idx = (idx + 1) % imgs.length;
setTimeout(showOne, sleep);
}
showOne();
})(theDiv, 5000);
var image = new Array('/img/1.jpg', '/img/2.jpg', '/img/3.jpg');
setTimeout("show_next()",5000);
function show_next()
{
var container = document.getElementById('image_container');
container.innerHTML = "<img src='" + image[i] + "' />";
if(i==2) { i = 1; }else { i = i + 1; }
}
I thought this was a nice simple answer, but there were a couple of errors.
setInterval rather than setTimeout and the initial index was not set. I also amended to load first image immediately.
var image = new Array('imgs/18/P1050294-XL.jpg', 'imgs/18/P1050293-XL.jpg', 'imgs/18/P1040984-XL.jpg', 'imgs/18/P1040983-XL.jpg', 'imgs/18/P1040982-XL.jpg');
var path = 'mypath';
document.getElementById('slideShow').innerHTML = "<img width='600px' src='" + path + image[0] + "' />" // Load First image
var i = 1; // Set counter to second image, for first use of loop
setInterval("show_next(path)",5000);
function show_next(path)
{
var container = document.getElementById('slideShow');
container.innerHTML = "<img width='600px' src='" + path + image[i] + "' />";
if(i==4) { i = 0; } else { i = i + 1; }
}

Categories