I'm trying to create an automatic slideshow in HTML and JavaScript, but the code is making my entire webpage blank.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page title</title>
<link rel="stylesheet" href="4.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div >
<div >
<img src="effiel tower.png" alt="">
<img src="Capetown.png" alt="">
<img src="china mountain.png" alt="">
</div>
</div>
The images on the HTML are working fine, but as soon as I enter the JavaScript code it gives me a blank page.
<script>
window.onload = function(){
var index = 0;
show ();
function show(){
var i;
var slides = document.getElementsByClassName("slides");
for(i=0;i<slides.length; i ){
slides[i].style.display ="none"
}
index=index 1;
if(index>slides.length){
index=1;
}
slides[index-1].style.display = "block";
setTimeout(show, 1500);
}
}
</script>
</body>
</html>
CodePudding user response:
you selected the parent of the images. It means you are hiding parent. Not images. add class to your images and select them by getElementsByClassName.
CodePudding user response:
let index = 0;
const slides = document.querySelectorAll('.slides > img');
function showSlideAt(index) {
for(let i=0;i<slides.length; i ){
const slide = slides[i];
slide.style.display = i === index ? "block" : "none";
}
}
showSlideAt(0);
setInterval(() => {
index = (index 1) % slides.length;
showSlideAt(index);
}, 1500)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Page title</title>
<link rel="stylesheet" href="4.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div >
<div >
<img src="https://www.gravatar.com/avatar/12a357d653e4cf98f3d3f06f122c2c1f?s=64&d=identicon&r=PG" height="100">
<img src="https://www.gravatar.com/avatar/fd4522e30ca42954b37fcc3b4072c3f9?s=48&d=identicon&r=PG&f=1" height="100">
</div>
</div>
</body>
</html>