How To Add Several Read More And Read Less Buttons Through Javascript Using GetElementsById Or ClassName?
everyone. Recently, I have been working to add 'Read More' and 'Read Less' buttons through Javascript. I am able to do that only once for one specific element by picking its ID. Bu
Solution 1:
You can toggle a class to show/hide the spans, using some CSS, like this:
document.querySelectorAll(".showmore").forEach(function (p) {
p.querySelector("a").addEventListener("click", function () {
p.classList.toggle("show");
this.textContent = p.classList.contains("show") ? "Show Less" : "Show More";
});
});
.showmore {
font-size: 1.1em;
margin-top: 1.5em;
}
.showmore .more, .showmore.show .dots {
display: none
}
.showmore.show .more {
display: inline
}
.showmore a {
cursor: pointer;
display: block;
margin-top: 0.5em;
margin-bottom: 1em;
font-weight: bold;
}
<p class="showmore">This is Lorem Ipsum. This is Lorem Ipsum. <span class="dots">...</span><span class="more"> This is the hidden text. This is the hidden text. </span>
<a>Show More</a>
</p>
<p class="showmore">And here is a second paragraph. <span class="dots">...</span><span class="more"> This is the hidden text. This is the hidden text. </span>
<a>Show More</a>
</p>
The code first loops over all paragraphs, then grabs the <a>
inside and assigns the click handler.
Post a Comment for "How To Add Several Read More And Read Less Buttons Through Javascript Using GetElementsById Or ClassName?"