This is a simple webpage I am building for personal use. The goal is to make each section clickable: the clicked section will expand using animation code that is not yet added, and the other elements will be hidden. Clicking the same element will cause it to return to the original size, and the other elements to once again be visible. However, the current code always causes the first .item
element to remain and hides the others, regardless of which element is clicked.
let isExpanded = false;
const items = document.querySelectorAll(".item");
items.forEach(e => {
e.addEventListener("click", event => {
if (isExpanded === false) {
items.forEach(f => {
console.log(f.dataset.index);
console.log(event.target.closest("[data-index]").dataset.index);
if (f.dataset.index !== event.target.closest("[data-index]").dataset.index) {
f.style.display = "none";
}
});
isExpanded = true;
} else {
items.forEach(g => {
g.style.display = "inline-block";
});
isExpanded = false;
}
})
});
* {
font-family: Verdana, Geneva, Tahoma, sans-serif;
}
body {
background-color: #0066ff;
}
#title {
color: white;
}
#list {
width: 90%;
margin: auto;
}
.item {
display: inline-block;
width: 20%;
margin: 20px;
padding: 0 10px;
border: solid 7px blue;
border-radius: 3px;
background-color: white;
}
<h1 id="title">
「今週の英語フレーズ」履歴
</h1>
<div id="list">
<div class="item" data-index="1">
<h2>10/10/2024</h2>
<p>フレーズ:How are you?</p>
<p>和訳:お元気ですか?</p>
<p>動画:</p>
</div>
<div class="item" data-index="2">
<h2>10/10/2024</h2>
<p>フレーズ:How are you?</p>
<p>和訳:お元気ですか?</p>
<p>動画:</p>
</div>
<div class="item" data-index="3">
<h2>10/10/2024</h2>
<p>フレーズ:How are you?</p>
<p>和訳:お元気ですか?</p>
<p>動画:</p>
</div>
<div class="item" data-index="4">
<h2>10/10/2024</h2>
<p>フレーズ:How are you?</p>
<p>和訳:お元気ですか?</p>
<p>動画:</p>
</div>
</div>
2
Answers
Try this, you can handle most of it using CSS.
Here you go. Only the clicked one will be visible, others will be hidden. Clicking again will bring them back.