How to make multiple read more buttons in same page using one jquery?
Problem
You are adding multiple elements with the same id
, this is not appropriate and means that when you write your javascript there are errors. By using the id
the code cannot tell the difference between different elements that are related - i.e. is expanding the wrong text. You are also not telling the code about the relationship between the clicked element and the element to be shown/hidden.
Solution
Use classes for each of your elements - i.e. toggle-text-button
for the links that triger the showing or hiding of elements with the class .toggle-text
.
I have used the following code to move from the <a class="toggle-text-button">Read More</a>
to the appropriate elements:
$(this).parent().children(".toggle-text").slideDown();
Code explaination:
$(this)
jquery notation, telling the code to start with the element currently in focus (i.e. the one clicked).parent()
move up the DOM tree one element (an alternative would be.closest()
that continues to move up until the selector condition is met).children(".toggle-text")
find all children of the current element (as we have moved up the DOM tree this is the parent of the clicked element), that match the selector.slideDown()
slide down any elements that match the previous series of selectors
Demo
// Add click event dynamically$(document).on("click", ".toggle-text-button", function() {
// Check if text is more or less if ($(this).text() == "Read More") {
// Change link text $(this).text("Read Less"); // Travel up DOM tree to parent, then find any children with CLASS .toggle-text and slide down $(this).parent().children(".toggle-text").slideDown(); } else {
// Change link text $(this).text("Read More"); // Travel up DOM tree to parent, then find any children with CLASS .toggle-text and slide up $(this).parent().children(".toggle-text").slideUp(); } });
.toggle-text { display: none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.25/js/uikit-icons.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.25/js/uikit.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-rc.25/css/uikit.min.css" rel="stylesheet" /><div class="uk-section uk-section-small uk-section-default"> <div class="uk-container"> <h2 class="heading-primary uk-text-center "><span>Guide</span></h2> <div class="uk-grid-divider uk-child-width-expand uk-margin-medium-top uk-margin-mediumm-bottom" uk-grid> <div> <div class="uk-text-left" uk-grid> <div class="uk-width-1-4@s uk-text-center"> <img class="uk-border-square" src="https://source.unsplash.com/200x200?face" alt="Border square"> </div> <div class="uk-width-3-4@s"> <h1 style="display: inline">Name</h1> <h2 style="display: inline; font-style: italic;">(Designation)</h2> <p class="uk-text-justify">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque officia optio nostrum voluptas, rem error nulla sed illo eveniet quasi.</p> <p class="uk-text-justify toggle-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate repellat quae in nobis laborum laboriosam praesentium molestiae, aliquam maxime modi eos ab voluptatibus magnam, provident, dolorum, dolore adipisci! Qui dignissimos illum voluptate omnis similique repellendus. Quas quam assumenda aliquid quos expedita, sit dolorem eveniet omnis.</p><a class="toggle-text-button">Read More</a> </div> </div> <div class="uk-width-1-4@s uk-text-center"> <img class="uk-border-square" src="https://source.unsplash.com/200x200?face" alt="Border square"> </div> <div class="uk-width-3-4@s"> <h1 style="display: inline">Name</h1> <h2 style="display: inline; font-style: italic;">(Designation)</h2> <p class="uk-text-justify">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque officia optio nostrum voluptas, rem error nulla sed illo eveniet quasi.</p> <p class="uk-text-justify toggle-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate repellat quae in nobis laborum laboriosam praesentium molestiae, aliquam maxime modi eos ab voluptatibus magnam, provident, dolorum, dolore adipisci! Qui dignissimos illum voluptate omnis similique repellendus. Quas quam assumenda aliquid quos expedita, sit dolorem eveniet omnis.</p><a class="toggle-text-button">Read More</a> </div> </div> <div class="uk-width-1-4@s uk-text-center"> <img class="uk-border-square" src="https://source.unsplash.com/200x200?face" alt="Border square"> </div> <div class="uk-width-3-4@s"> <h1 style="display: inline">Name</h1> <h2 style="display: inline; font-style: italic;">(Designation)</h2> <p class="uk-text-justify">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque officia optio nostrum voluptas, rem error nulla sed illo eveniet quasi.</p> <p class="uk-text-justify toggle-text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate repellat quae in nobis laborum laboriosam praesentium molestiae, aliquam maxime modi eos ab voluptatibus magnam, provident, dolorum, dolore adipisci! Qui dignissimos illum voluptate omnis similique repellendus. Quas quam assumenda aliquid quos expedita, sit dolorem eveniet omnis.</p><a class="toggle-text-button">Read More</a> </div> </div> </div> </div> </div></div>
How to add several Read More and Read Less buttons through Javascript using getElementsById or ClassName?
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>
Multiple readmore buttons working at the same time
Since you want the readmore
state to be applied to the individual boxes you could store an array in the state and check, if the id
is set, but I would go with the (in my opinion) simpler way:
Extract your block into its own component, which has its own state readmore
like so:
<section className="escritos">
{escritos.map(escrito => (
<Escrito escrito={escrito} key={escrito.id} />
))}
</section>
// Escrito.jsx
const Escrito = ({escrito}) => {
const [readmore, setReadmore] = useState(false);
return (
<div>
<p>
Autor: <strong>{escrito.autor}</strong>
</p>
<p>
{" "}
Título: <strong>{escrito.titulo}</strong>
</p>
<div id="obras">
{" "}
{readmore
? parse(escrito.escrito)
: parse(escrito.escrito.substring(0, 200))}
<button id="readmore" onClick={() => setReadmore(!readmore)}>
{readmore ? "ler menos" : "ler mais"}
</button>
<Link to="#beginning">
<BsFillArrowUpCircleFill />
</Link>
</div>
<hr />
</div>
);
}
export default Escrito;
Since each component now has its own state, this should be the behavior you want.
How do i create multiple read more and less buttons for the same page?
I was thinking of a different approach, maybe using tabs in JS.
I edited the snippet with your actual content so you can see how it is displayed. Reference here:
https://www.w3schools.com/howto/howto_js_tabs.asp
function openDef(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active";}
.tab { overflow: hidden; border: 1px solid #ccc; background-color: #f1f1f1;}
.tab button { background-color: inherit; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; transition: 0.3s; font-size: 17px;}
.tab button:hover { background-color: #ddd;}
.tab button.active { background-color: #ccc;}
.tabcontent { display: none; padding: 6px 12px; border: 1px solid #ccc; border-top: none;}
<div class="tab"> <button class="tablinks" onclick="openDef(event, 'Sighthounds')">Sighthounds</button> <button class="tablinks" onclick="openDef(event, 'Origin')">Origin</button></div>
<div id="Sighthounds" class="tabcontent"> <h3>Sighthounds</h3> <h3>The Sighthounds</h3> <p> By definition, a sighthound is simply a dog breed that hunts primarily by sight and speed rather than by scent because of this they are sometimes refered to as Gazehounds. Because sighthounds hunt by sight, they need to have the speed and agility to keep up with their prey in order to keep them in sight. Sighthound breeds typically have lean bodies, long legs, and a flexible back – they also have deep chests to support their unusually large hearts and lungs. To help you picture the typical sighthound body, here is a list of breeds that are categorized as sighthounds:
<h4>Afghan Hound:</h4> <p> Wow very biscit stop it fren very hand that feed shibe heckin, many pats. Shooberino h*ck blep shoob sub woofer very taste wow shoober, snoot heckin mlem smol borking doggo with a long snoot for pats. Heck I am bekom fat pupperino borkdrive length boy, such treat maximum borkdrive wow very biscit. Borking doggo clouds much ruin diet pupperino tungg super chub, very hand that feed shibe you are doin me a concern boofers
<span class="dots">...</span></div>
<div id="Origin" class="tabcontent"> <h3>Origin</h3> <h5>Origin</h5> <p> Doggo ipsum smol borking doggo with a long snoot for pats bork mlem heckin much ruin diet lotsa pats I am bekom fat, doing me a frighten most angery pupper I have ever seen pats waggy wags vvv. big ol pupper big ol. Ur givin me a spook smol borking doggo with a long snoot for pats big ol pupper long bois ur givin me a spook bork smol adorable doggo, the neighborhood pupper doing me a frighten puggorino tungg ur givin me a spook. Blep the neighborhood pupper heckin good boys big ol pupper noodle horse, doge big ol blep. noodle horse shibe maximum borkdrive. Bork you are doing me a frighten boof pats, noodle horse extremely cuuuuuute you are doing me the shock borkf, boof borkf. </p>
<h4>Azwakah:</h4> <p> Wow very biscit stop it fren very hand that feed shibe heckin, many pats. Shooberino h*ck blep shoob sub woofer very taste wow shoober, snoot heckin mlem smol borking doggo with a long snoot for pats. Heck I am bekom fat pupperino borkdrive length boy, such treat maximum borkdrive wow very biscit. Borking doggo clouds much ruin diet pupperino tungg super chub, very hand that feed shibe you are doin me a concern boofers <span class="dots">...</span> </div>
Related Topics
How to Check If Text Is Truncated by CSS Using JavaScript
Replacing Normal File Upload Input with an Image
Saving Dropdown Menu Selection in a Cookie
Screen Zooms in When a Bootstrap Modal Is Opened on iOS 9 Safari
Detect Support for Background-Attachment: Fixed
Position Sticky: Scrollable, When Longer Than Viewport
How to Check That an Element Is Visible with Puppeteer and Pure JavaScript
Opening an External Website in a Modal Popup
Gulp with Gulp-Ruby-Sass: Error: ../Style.Css.Map:3:1: Unknown Word
How to Make Specific Part of a String Bold in Angular 2
How to Show/Hide Big Image by Clicking on Thumbnails
Tinymce Customize "File" Menubar
How to Use Jquery to Detect If a File Input Has a File Selected
CSS :Hover on Mobile or Other Device as Toggle
How to Dynamically Change the Style Tag Using JavaScript
How to More Accurately Measure Svg Text Height
Detect If Visitor Is on Index Page with Client Side Scripting