Issue
so what I am trying to create is a content slideshow. I have five html elements that are absolute
positioned. The idea is to have elements hidden except the first one, then using setInterval
i would like to add the hide class to to the all the elements except the one in current view.
here is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="/script.js" defer></script>
</head>
<body>
<div class="card first">first</div>
<div class="card second ">second</div>
<div class="card third ">third</div>
<div class="card fourth ">fourth</div>
<div class="card fifth ">fifth</div>
</body>
</html>
*{
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
position: relative;
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
}
/* card will contain the general properties of the card element */
.card{
position: absolute;
width: 60%;
height: 70%;
}
/* below will contain the individual properties of a card element */
.first{
background-color: red;
}
.second{
background-color: rgb(68, 97, 177);
}
.third{
background-color: rgb(27, 221, 20);
}
.fourth{
background-color: rgb(187, 0, 109);
}
.fifth{
background-color: rgb(184, 204, 0);
}
.hide{
display: none;
}
and the javascript that i have
const containerElement = document.querySelectorAll('.card')
setInterval(() => {
for (let i = 0; i < containerElement.length; i++) {
containerElement[i].classList.add('hide')
}
}, 5000);
The javascript I have noticed adds the class hide
at the same time instead of gradually after 5 seconds each. Thanks.
Solution
An easy way to do this is with a function called using setTimeout
const containerElement = document.querySelectorAll('.card');
function fn(i) {
containerElement[i].classList.add('hide')
if (i < containerElement.length - 1) {
setTimeout(fn, 5000, i + 1);
}
}
setTimeout(fn, 5000, 0);
Answered By - Jaromanda X
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.