I have four child divs inside the container div, every child div has a button, image, and text inside. Images have to be blurry and text has to be hidden by default.
And when the user clicks the button, the button should be hidden, image and text should become clear and visible.
I'm trying to add or remove CSS classes from elements using for loop, but that just doesn't work at all...
let btns = document.querySelectorAll(".btn");
let images = document.querySelectorAll(".img");
let imgTexts = document.querySelectorAll(".img-text");
images.forEach((el) => el.classList.add("blur"));
imgTexts.forEach((el) => el.classList.add("hidden"));
for (let i = 0; i < btns; i++) {
btns[i].addEventListener("click", function () {
btns[i].classList.add("hidden");
});
}
.blur {
filter: blur(8px);
-webkit-filter: blur(8px);
}
.hidden {
display: none;
}
<div class="container">
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
</div>
for (let i = 0; i < btns; i++) {
btns[i].addEventListener("click", function () {
btns[i].classList.add("hidden");
});
}
Here, in the conditions of the for loop, write "i < btns.length".
There is not a boundation that you can create only one class. You can create multiple classes and just on and add and remove the class according to your need. example code HTML
<img class = "image imageHidden" src = alt = >
<button class = "button buttonHidden">Click me</button>
now I created two classes at the same time I can use them to my need in javascript CSS
.image {
visiblity: visible}
.imageHidden {
visibility: hidden}
.button {
visibility: visible}
.buttonHidden {
visibility: hidden}
now I used them in CSS that I can use in javascript
document.querySelector(".button").addEventListener("click",function () {
document.querySelector("img").classList.add("image");
document.querySelector("button").classList.add("buttonHidden");});
this code will hide the button and show the image you can use this method according to your need.