I have written a function to display or not display the title of an element.
My code works correctly. But only the first element reacts to my code and other elements don’t react to my code.
My codes are as follows:
let eye = document.querySelector(".box_icon");
let excerpt = document.querySelector(".title_box");
eye.addEventListener("click", function() {
if (this.classList.contains("bi-play-circle-fill")) {
this.classList = "bi bi-power box_icon";
excerpt.style.display = "block";
} else {
this.classList = "bi bi-play-circle-fill box_icon";
excerpt.style.display = "none"
}
});
.box_main {
display: flex;
justify-content: space-around;
}
.box_mini {
width: 250px;
height: 200px;
background: #5ec7ff;
box-shadow: 0 0 4px #000;
}
.box_icon {
font-size: 25px;
margin: 10px 40% 6px;
color: #7f7f7f;
}
.title_box {
font-size: 45px;
margin: 25px 15px 20px;
color: #f9ff4d;
display: none;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" rel="stylesheet" />
<section class="box_main">
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
<div class="box_mini">
<i class="bi bi-play-circle-fill box_icon"></i>
<h1 class="title_box">Title BOX</h1>
</div>
</section>
Please guide me to edit the java script code I wrote.
2
Answers
Delegate and toggle
Alternative to
title.hidden = !on;
could betitle.classList.toggle("show",on)
if you want to use display:block/none classesYou could use
querySelectorAll
, then loop on each matched element to add event listener.Another method is to add event listener on container element, then check event’s target element. If it’s the box icon, we will hide/show corresponding elements.