I'm fairly new to JS. So, pardon me for asking such stupid question.
I want to implement a Read more/ less button based on this article.
This worked perfectly fine, because it had unique id. But when I implement this in a multiple read more blocks with same id, it triggers only the first element.
I have two div with id card1 and card2 under the parent div of class wrapper. I want to show clicked read more div (let say of card1) and hide the other div (card2) completely (and vice-versa).
Here's my code.
As you can see, it works perfectly fine for the first div (card1), but due to the contradiction of using same id, it doesn't work for other div.
It is possible, to call id specifically of parent div where the button is clicked and ignore the elements of other div with the same id. Is there any other simple way to solve my problem?
So far I don't know jQuery, so, solving the problem with pure JS will be very helpful.
Thank you.
function myFunction(t) {
var x = document.getElementById(t.id).parentNode;
var y = x.parentNode;
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
y.style.visibility = "visible";
} else {
y.style.visibility = "hidden";
x.style.visibility = "visible";
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
#more {
display: none;
}
<div class="wrapper">
<div id="card1">
<h2>Read More Read Less </h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" id="myBtn">Read more</button>
</div>
<div id="card2">
<h2>Read More Read Less 2</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" id="myBtn">Read more</button>
</div>
</div>