I am building this web using the laravel framework and I am not good at js tricks as I need to list todo titles only but when the user clicks on them it shows its own content. so far it only works for the last one.
<div class="container-fluid">
<h1>Painted List <a href="/create" class="text-success"><i class="fa fa-plus"></i></a></h1>
<ul>
@if(count($paints) > 0)
@foreach($paints as $paint)
<li onclick="myFunction()"><span><i class="fa fa-trash"></i></span> {{ $paint->title }}</li>
<div class="card-body" id="contentBody">
<p class="content"> {{$paint->content}} </p>
</div>
<script>
function myFunction() {
var x = document.getElementById("contentBody");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
@endforeach
@else
<li><span><i class="fa fa-trash"></i></span> No Paint yet!</li>
@endif
</ul>
</div>
that is my code I hope someone gonna helps me to show and hide using CSS, javascript, and HTML
As one helped and now it shows content when clicked but not one content at a time In this photo shows that I have clicked in both headers and all content from two headers are shown ut that is not what I want
CodePudding user response:
Put onclick in div inside <li> to allow return to parent <li> and put card-body element inside <li> and use <script> outside foreach to avoid repetition.
Try this:
<div class="container-fluid">
<h1>Painted List <a href="/create" class="text-success"><i class="fa fa-plus"></i></a></h1>
<ul>
@if(count($paints) > 0)
@foreach($paints as $paint)
<li>
<div onclick="myFunction(this)"><span><i class="fa fa-trash"></i></span> {{ $paint->title }}</div>
<div class="card-body" id="contentBody">
<p class="content"> {{$paint->content}} </p>
</div>
</li>
@endforeach
<script>
function myFunction(el) {
var p = el.parentNode; // return from div you clicked it to <li>
var x = p.querySelector('.card-body'); // find card-body
//var x = document.getElementById("contentBody");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
@else
<li><span><i class="fa fa-trash"></i></span> No Paint yet!</li>
@endif
</ul>