I’m trying to implement Readmore/readless functionality for a Laravel feed page that returns many objects from DB. The problem is my readmore code only works for the first object but doesn’t work on subsequent objects. It’s kind of a Facebook feed page where you can view posts from friends and then click the "Readmore" button to expand a comment or a note. That’s precisely what I’m trying to implement. My "Readmore" code works only for the first object. I’d like some help with making the "Readmore" button apply to all objects from the DB.
Below is my code
**HTML**
<div class="container row">
@forelse ($counters as $key => $counter)
<div>
<h6>Title</h6>
<p>{{ $counter->title }}</p>
</div>
<div>
<h6>Address</h6>
<p>{{ $counter->address }}</p>
</div><span id="dots"></span><span id="moretext">
<div>
<h6>Email</h6>
<p>{{ $counter->email }}</p>
</div>
<div>
<h6>Contact no.</h6>
<p>{{ $counter->contact }}</p>
</div>
</span><button onclick="myFunction()" id="myBtn">Read more</button>
@empty
No information published yet.
@endforelse
</div>
**CSS**
<style>
#moretext {display: none;}
</style>
**JS**
<script>
function myFunction() {
var dots = document.getElementById("dots");
var moreText = document.getElementById("moretext");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
}
else
{
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
</script>
2
Answers
IDs need to be unique. Use a class.
Your HTML is invalid. A span cannot contain a div. Make it a div and wrap your content and you can use delegation like this
Your code:
Ids need to be unique
This is the code you are looking for