I have a for each loop in blade file that display items .
What I want when one element name clicked only same item be toggle but my code toggle all items .
how to solve it?
the problem is my JavaScript code
var isHidden = true;
function loadToggleAction() {
var sheet = document.createElement('style')
if (!isHidden) {
sheet.innerHTML = ".show {display:none;}";
} else {
sheet.innerHTML = ".show {display:block;}";
}
document.body.appendChild(sheet);
isHidden = !isHidden;
}
<h2 class="lesson-h2" onclick="loadToggleAction()">
lesson 1
</h2>
<a class="lesson-file" href="{{ " #play " }}">
<img class="show-lesson" src="img.png" title="مشاهده آنلاین این درس" height="24" onclick="loadToggleAction()">
</a>
<div class="show">
lesson 1 content
</div>
<h2 class="lesson-h2" onclick="loadToggleAction()">
lesson 2
</h2>
<a class="lesson-file" href="{{ " #play " }}">
<img class="show-lesson" src="img.png" title="مشاهده آنلاین این درس" height="24" onclick="loadToggleAction()">
</a>
<div class="show">
lesson 2 content
</div>
<h2 class="lesson-h2" onclick="loadToggleAction()">
lesson 3
</h2>
<a class="lesson-file" href="{{ " #play " }}">
<img class="show-lesson" src="img.png" title="مشاهده آنلاین این درس" height="24" onclick="loadToggleAction()">
</a>
<div class="show">
lesson 3 content
</div>
If you want to do this with CSS, you need to calculate an id to your lesson-h2 component while iterate (you can do this using the index in a for loop.
Once you do that, you can change the display style on the ID directly in your loadToggleAction() function (and not on the class as you do actually).
You need to delegate
I do not recommend creating styles since this is much simpler and works
document.getElementById('container').addEventListener('click', function(e) {
e.preventDefault()
const tgt = e.target.closest('a');
if (tgt && tgt.classList.contains('lesson-file')) {
tgt.nextElementSibling.classList.toggle('hide')
}
})
.hide { display:none; }
<div id="container">
<h2 class="lesson-h2">
lesson 1
</h2>
<a class="lesson-file" href="{{ " #play " }}">
<img class="show-lesson" src="img.png" title="مشاهده آنلاین این درس" height="24" />
</a>
<div class="hide">
lesson 1 content
</div>
<h2 class="lesson-h2">
lesson 2
</h2>
<a class="lesson-file" href="{{ " #play " }}">
<img class="show-lesson" src="img.png" title="مشاهده آنلاین این درس" height="24" />
</a>
<div class="hide">
lesson 2 content
</div>
<h2 class="lesson-h2">
lesson 3
</h2>
<a class="lesson-file" href="{{ " #play " }}">
<img class="show-lesson" src="img.png" title="مشاهده آنلاین این درس" height="24" />
</a>
<div class="hide">
lesson 3 content
</div>
</div>