How to change an image every 5 seconds for example? - javascript

I have three images in my HTML code, and I want them to change every five seconds. Why does my code not work?
var images = [];
images[0] = ['photoFromInternet'];
images[1] = ['photoFromInternet2'];
images[2] = ['photoFromInternet3'];
var index = 0;
function change() {
document.mainPhoto.src = images[index];
if (index == 2) {
index = 0;
} else {
index++;
}
setInterval(change(), 1000);
}
window.onload = change();
<div class="lastMain">
<a href="www.comingsoon.com" id="slider">
<img id="mainPhoto">
<div class="mainSlider">
<img src="photoFromInternet1" style="display: none">
<img src="photoFromInternet2*" style="display: none">
<img src="photoFromInternet3" style="display: none">
</div>
</a>
</div>
P.S. If you can help please don't use jquery because I haven't learned that yet.

you should run 'change' function outside of the func and pass the function name to the setInterval func as below
let images = ['photoFromInternet', 'photoFromInternet2', 'photoFromInternet3'];
let index = 0;
const imgElement = document.querySelector('#mainPhoto');
function change() {
imgElement.src = images[index];
index > 1 ? index = 0 : index++;
}
window.onload = function () {
setInterval(change, 5000);
};

Look at your console, it's telling you why. Uncaught TypeError: Cannot set property 'src' of undefined, meaning document.mainPhoto is undefined. That's not how you select an element in JS (document.getElementById("mainPhoto") works better :)
Also, you should pass a function to setInterval, not call the function directly inside of it, otherwise you are infinitely calling change() which leads to an infinite call stack error.
Also, if you want 5 seconds, you want to pass 5000, not 1000 (milliseconds).
Finally, you want to set a timeout, not an interval, every time you call the function. Timeouts are executed once. If you set a new interval every time, you'll be piling up function calls exponentially, quickly making your page unresponsive by overwhelming the CPU.
var images = [];
images[0] = ['photoFromInternet'];
images[1] = ['photoFromInternet2'];
images[2] = ['photoFromInternet3'];
var index = 0;
function change() {
document.getElementById("mainPhoto").src = images[index];
if (index == 2) {
index = 0;
} else {
index++;
}
setTimeout(change, 5000);
}
window.onload = change();
<div class="lastMain">
<a href="www.comingsoon.com" id="slider">
<img id="mainPhoto">
<div class="mainSlider">
<img src="photoFromInternet1" style="display: none">
<img src="photoFromInternet2*" style="display: none">
<img src="photoFromInternet3" style="display: none">
</div>
</a>
</div>

Related

why the control button do not work in my slideshow?

I make slideshow width 4 photos that appear with opacity: 1 and z-index: 2, and I could make it run automatically, but to control it, not yet and this is my js code with some of jquery:
$(document).ready(function() {
var i = 0
function next() {
move(i++);
if (i === 4) {
i = 0
}
console.log("first i = " + i)
};
setInterval(next, 2000);
function move(n) {
var images = document.querySelectorAll('img')
var img = images[n]
$(img).addClass('showSlide')
$(img).removeClass('hideSlide')
$(img).siblings(".img").addClass('hideSlide')
}
$('.next').click(
() => {
if (i === 3) {
i = 0
};
move(i++);
console.log("next i = " + i)
}
)
$('.previous').click(
() => {
if (i === 0) {
i = 3
};
move(i--);
console.log("previous i = " + i)
}
)})
my automatic slide work but when I click the next or the previous button the slide do not continue from the last position ,and my HTML code is :
<div class="container">
<button class="next">next</button>
<button class="previous">previous</button>
<img class="img" src="gallery-img7.jpg" alt="">
<img class="img" src="gallery-img2.jpg" alt="">
<img class="img" src="gallery-img8.jpg" alt="">
<img class="img" src="gallery-img3.jpg" alt="">
</div>
I think the way you are handling increment and decriment might be the issue? This is a good use case for modulo %. I also cleared and reset the interval after button click to get the same interval on the newly shown image. Here's an example that seems to work as your intending:
$(document).ready(function() {
var i = 0
function next() {
move(i++);
};
let nextInterval = setInterval(next, 2000);
function move(n) {
clearInterval(nextInterval)
nextInterval = setInterval(next, 2000);
n = i%4;
var images = document.querySelectorAll('img')
var img = images[n]
$(img).addClass('showSlide')
$(img).removeClass('hideSlide')
$(img).siblings(".img").addClass('hideSlide')
}
$('.next').click(
() => {
move(i++);
}
)
$('.previous').click(
() => {
move(i--);
}
)})
.img{
display:block;
width:100px;
height:100px;
}
.showSlide{
display:block;
}
.hideSlide{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<button class="next">next</button>
<button class="previous">previous</button>
<img class="img" src="https://via.placeholder.com/100x100.png?text=1" alt="">
<img class="img hideSlide" src="https://via.placeholder.com/100x100.png?text=2" alt="">
<img class="img hideSlide" src="https://via.placeholder.com/100x100.png?text=3" alt="">
<img class="img hideSlide" src="https://via.placeholder.com/100x100.png?text=4" alt="">
</div>
I think your code to trigger the next and previous clicks is basically working, the Interval function you are running is never interrupted by your button clicks, so the slideshow continues to cycle around.
Your classes to show and hide may not be attaching to the DOM properly either. I find it's a good practice to attach less specific classes before I attach a specific one, i.e. blanket hide all slides and then show the selected slide.
Another technique that I think is helpful is to try and figure out the manual user interaction first and then base my automation on it. I've worked up an alteration of the code you posted, where the slides 'slide' themselves by triggering the next action, similarly to how a user would.
So the slideshow should start itself on page load by use of a setInterval being declared. That setInterval is interrupted when the user moves the mouse into the slideshow area - this way the button will control the active/shown slide. If you move the mouse off or away from the slideshow container the setInterval is allowed to kick in again, and the slides should cycle around automatically.
$(document).ready(function() {
var i = 0;
function move(n) {
var images = document.querySelectorAll('img');
var img = images[n];
$(img).siblings(".img").addClass('hideSlide');
$(img).siblings(".img").removeClass('showSlide');
$(img).addClass('showSlide');
$(img).removeClass('hideSlide');
}
var next = setInterval(autoRotate, 2000);
function autoRotate() {
$('.next').trigger('click');
}
$('.container').on('mouseenter', function() {
clearInterval(next);
});
$('.container').on('mouseleave', function() {
next = setInterval(autoRotate, 2000);
});
$('.next').click(() => {
if (i === 3) {
i = 0;
} else {
i++;
}
move(i);
});
$('.previous').click(() => {
if (i === 0) {
i = 3;
} else {
i--;
}
move(i);
});
})

Display 6 (distinct) images from an array, don't show duplicates and reload every x seconds

I have 12 images in total. I want to display a maximum of 6 distinctive images at any one time - without showing duplicates. To do this I am using jQuery. I want the images to change/rotate every 5 seconds.
I can't seem to get this code to work. Can someone please show me where I am going wrong?
var imagesArray = [
imgs / Scan1.jpeg ',
'../imgs/Scan2.jpeg',
'../imgs/Scan3.jpeg',
'../imgs/Scan4.jpeg',
'../imgs/Scan5.jpeg',
'../imgs/Scan6.jpeg',
'../imgs/Scan7.jpeg',
'../imgs/Scan8.jpeg',
'../imgs/Scan9.jpeg',
'../imgs/Scan10.jpeg',
'../imgs/Scan11.jpeg',
'../imgs/Scan12.jepg',
];
var usedImages = {};
var usedImagesCount = 0;
function displayImage() {
var num = Math.floor(Math.random() * (imagesArray.length));
if (!usedImages[num]) {
document.canvas.src = imagesArray[num];
usedImages[num] = true;
usedImagesCount++;
if (usedImagesCount === imagesArray.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
setInterval(function() {
$("#deluxe_img").attr("src", displayImage(););
}, 5000);
}
}
<div class="premium_listing_container">
<img src="function(displayImage())" id="deluxe_img" />
<img src="function(displayImage())" id="deluxe_img" />
<img src="function(displayImage())" id="deluxe_img" />
<img src="function(displayImage())" id="deluxe_img" />
<img src="function(displayImage())" id="deluxe_img" />
<img src="function(displayImage())" id="deluxe_img" />
</div>
As Christian Hain pointed out in the comment, id are supposed to be unique while you have 6 img with the same id. You must use classes for these situations.
If you use the string function(displayImage()) as attribute, your browser will look for a image called exactly function(displayImage()) and will not evaluate it as Javascript, because it doesn't understand it is javascript code. You need to use the javascript line for changing them also on the first page load to set the initial values:
$(".deluxe_img").attr("src", displayImage());
Why do you set the interval everytime that !usedImages[num] evaluates to false? This will keep generating new interval, so your code will constantly be running and not only once every 5 seconds. You need to handle the case when !usedImages[num] evaluates to false by looking for a different num
var imageIndexes = [0,1,2,3,4,5,6,7,8,9,10,11]
function displayImage() {
var index = Math.floor(Math.random() * (imageIndexes.length));
var num = imageIndexes[index]
var result = imagesArray[num];
imageIndexes.splice(index, 1)
if (imageIndexes.length === 0) {
imageIndexes = [0,1,2,3,4,5,6,7,8,9,10,11]
}
return result
}
function changeImagesSrc() {
$(".deluxe_img").each(function () {
$(this).attr('src',displayImage())
})
}
$(document).ready(function () {
changeImagesSrc()
setInterval(function() {
changeImagesSrc()
}, 5000);
})

Anyway I can use the same script but for divs id tag instead of images?

Ive been trying to create this certain slideshow for a webpage I am making. Everytime Im trying to replace the images with an id tag, the slideshow freezes at the first picture. I just want a way to use the same method to create a slide show using div ids (since Im trying to write/edit on the panels). If there is an another method, please mention it also.
This is the code I am using for the images:
var pic = document.getElementById("car");
var Array = ["images/pic_1.jpg", "images/pic_2.jpg", "images/pic_3.jpg"];
var index = 0;
function myFunction() {
pic.setAttribute("src", Array[index]);
index++;
if (index >= Array.length) {
index = 0;
}
}
setInterval(myFunction, 1000);
Actually, you can use some parts of code (and basic idea), and do something like this:
var index = 0;
slides=document.querySelectorAll('.slide');
function myFunction() {
for(i=0;i<slides.length;i++) {
slides[i].style.display='none'; //hide all
}
slides[index].style.display='block'; //show current
index++;
if (index >= slides.length) {
index = 0;
}
}
setInterval(myFunction, 1000);
DEMO:
var index = 0;
slides=document.querySelectorAll('.slide');
function myFunction() {
for(i=0;i<slides.length;i++) {
slides[i].style.display='none'; //hide all
}
slides[index].style.display='block'; //show current
index++;
if (index >= slides.length) {
index = 0;
}
}
setInterval(myFunction, 1000);
.slide {
display:none;
position:absolute;
}
<div id="container">
<div class="slide">
111111
</div>
<div class="slide">
222222222
</div>
<div class="slide">
333333333333
</div>
</div>
Don't call your Array an... Array because it's a keyword for JavaScript Array Object. Try something like that:
var cars = ["images/pic_1.jpg","images/pic_2.jpg","images/pic_3.jpg"]
(...)
pic.setAttribute("src" , cars[index])
It should help.

JavaScript Timeout Function

I was looking in other posts for the answer, but the answers never seem to work in my favor. I'm trying to make an image fade when the page finishes loading. I've figured out I can loop until the counter reaches 0 (when image is invisible) and fade the image slowly.
The problem is, the setTimeout() function doesn't seem to be working.
Here's the code:
function timeout() {
setTimeout(function () {
//A comment said something about looping,
//but it was confusing to understand...
}, 50);
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 0 //Start at being visible
for (var i = 10; i > 0; i = i - 0.1) { //For loop
load.style.opacity = i; //Use the index variable and use that to set the opacity
setTimeout(); //Set the timeout, but this function does not pause the program for some reason...
//I need to pause for 0.05 seconds.
}
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
I put the javascript in a seperate file, I just can't access it from Stack Overflow...
Can someone help? And also, sometimes the image can be finicky at times as well, like sometimes it won't hide like it's supposed to do. Thanks!
You declared a setTimeout without arguments, hence the error:
'Window': 1 argument required, but only 0 present."
Give it the appropriate amount of arguments:
for (var i = 10; i > 0; i = i - 0.1) { //For the loop
load.style.opacity = i;
setTimeout(functionName, milliseconds);
}
If you intended to use your timeout() function instead, call it. You're just instantiating a new setTimeout from the one you already created in the timeout() function.
You can use a recursive function instead of a loop
var load = document.getElementById('img');
function setup() {
load.style.opacity = "1"; //Start at being visible
timeout(1);
}
function timeout(i) {
setTimeout(function() {
i -= 0.1;
if(i<=0)
return;
load.style.opacity = i.toString();
timeout(i);
}, 200);
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div>
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150" id="img">
</div>
</body>
</html>
Basically you want to countdown the opacity with a recursive call. Here we are going from 1 down to 0 in 0.01 increments. The setTimeout will trigger the next recursive call after pausing for 50 msecs. These values, can of course, be adjusted as needed but the opacity needs to be a number from 1 (visible) to 0 (invisible).
function setOpacity(el, lvl) {
el.style.opacity = lvl;
}
function countDown(el, lvl) {
function action(el, lvl) {
return function () {
countDown(el, lvl);
}
}
setOpacity(el, lvl);
if (lvl > 0) {
lvl -= 0.01
setTimeout(action(el, lvl), 50);
}
}
function setup() {
var load = document.getElementById('img');
load.style.opacity = 1; //Start at being visible
countDown(load, 1);
}
window.addEventListener('load', setup, true);
<!DOCTYPE html>
<html>
<head>
<title>Webpage</title>
</head>
<body>
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>
</body>
</html>
function setup() {
var load = document.getElementById('img');
(function(){
var i = 1;
setTimeout(function () {
i -= 0.1;
load.style.opacity = i;
if (i > 0) {
setTimeout(arguments.callee, 100);
}
}, 100);
})();
}
window.addEventListener('load', setup, true); //Add event listener for when the page is done loading
<div id="img">
<img src="http://www.downgraf.com/wp-content/uploads/2014/09/01-progress.gif" width="200" height="150">
</div>

Javascript images slide

I am creating a website for my school project. I want to put some pictures in a slide show, but for some reason my code isnt working. Here is my code
<div class="row">
<div class="col-md-12">
<h3 class = "Contains">
<script type = "text/javascript">
var image1= new image()
image1.src=images/truck1.png
var image2= new image()
image2.src=images/truck4.png
var image3= new image()
image3.src=images/truck7.png
</script>
<img src="images/truck1.PNG" name = "slide" width ="400" height ="400">
<script>
var step =1;
function slideit(){
document.images.slide.src=eval("image"+step+".src");
if (step<3)
step++;
else
step=1;
setTimeout("slideit()", 2500);
}
slideit()
</script>
</h3>
</div>
A very basic and simple example of how you can step through an array
//Array of images
var Images = ['https://dummyimage.com/100x100/000/fff.jpg',
'https://dummyimage.com/200x200/000/fff.jpg',
'https://dummyimage.com/300x300/000/fff.jpg'
];
//Step counter
var step = 1;
function gallery() {
//change image
document.getElementById('Imgs').src = Images[step];
//Or you can use - document.images.slide.src=Images[step];
// is step more than the image array?
if (step < Images.length - 1) {
// No - add 1 for next image.
step++;
} else {
// Yes - Start from the first image
step = 0;
}
}
//When the ready, set interval.
window.onload = setInterval(gallery, 2500);
<img id="Imgs" name="slide" src="https://dummyimage.com/100x100/000/fff.jpg" />
The method you're trying will return the following errors in the browser console.
Uncaught ReferenceError: image is not defined(anonymous function)
Uncaught TypeError: Cannot read property 'src' of undefined
The browser console is your best friend when it comes to using javascript.
If you have any questions, please leave a comment below and I will get back to you as soon as possible.
If you want to stick with the same method here it is:
var step = 1;
var image1 = new Image();
image1.src = "https://dummyimage.com/100x100/000/fff.jpg";
var image2 = new Image();
image2.src = "https://dummyimage.com/200x200/000/fff.jpg";
var image3 = new Image();
image3.src = "https://dummyimage.com/300x300/000/fff.jpg";
function slideit() {
document.images.slide.src = window['image' + step].src;
if (step < 3)
step++;
else
step = 1;
setTimeout(slideit, 2500);
}
slideit();
<div class="row">
<div class="col-md-12">
<h3 class="Contains">
<img src="https://dummyimage.com/100x100/000/fff.jpg" name="slide" />
</h3>
</div>
I hope this helps. Happy coding!
Your problem is most probably in your "imagex.src=xxxxxxx". The images urls are string and must be quoted as such. So it should be :
image1.src="images/truck1.png"
Also, you try to call setTimeout with a string instead of a function reference/name. It should be :
setTimeout(slideit, 2500);
However, a setInterval would be best here instead of a setTimeout as it will call a function repetingly.
JS aside, there are some quirk in the HTML part. Mostly, you shouldn't use a H3 to wrap a div. H3 are ususaly used for page sub-titles, not for a 400x400 images ^^
As mentioned in your question comments, using eval is generaly a bad idea.
To Simplify, you could do something like this :
<div class="row">
<div class="col-md-12">
<div class="Contains">
<img src="images/truck1.PNG" name="slide" width="400" height="400">
<script>
var pictures = ["images/truck1.png",
"images/truck4.png",
"images/truck7.png"];
var step = 0;
function slideIt(){
if (step<3)
step++;
else
step=0;
document.images.slide.src=pictures[step];
}
setTimeout(slideit, 2500);
</script>
</div>
</div>
</div>

Categories