Is there a way to implement multiple "read more" and "read less" buttons on a single page?

I am currently working on a rather large project and I am encountering some issues with the read more buttons. As someone who is fairly new to JavaScript, I am still grappling with the concepts. While I have managed to make the function work for the first button, it does not seem to work for the others. Could you please point out where I might be going wrong?

$(document).ready(function() {
  $("#read").click(function() {
    $(this).prev().toggle();
    $(this).siblings('.dots').
    toggle("read");
    if ($(this).text() == 'Read More') {
      $(this).text('Read Less');
    } else {
      $(this).text('Read More');
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>The Hound Group</h1>
<div class="container">
  <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 class="showmore">
        <h5>Origin</h5>
        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>
    </div>
    <button type="button" id="read" class="btn btn-info btn-xs">Read More</button>

    <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 class="showmore">
        <h5>Origin</h5>
        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>
    </div>
    <button type="button" id="read" class="btn btn-info btn-xs">Read More</button>

While the script functions correctly for the first paragraph, it seems to falter for the second one. Can you shed some light on why this may be happening or suggest a better approach? Thank you

Answer №1

Perhaps a different strategy could be to utilize tabs in JavaScript for this task. I have made adjustments to the code snippet using your actual content so you can visualize how it appears. 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>

Answer №2

It is important to avoid using the same ID multiple times, such as id="read", as this is a common mistake. Another key point is to ensure that the structure of elements is well-separated. Each logical block should have its own parent element. Here is an example:

$(document).ready(function(){
   $(".read").click(function(){
      $(this).parent().find('.showmore').toggle();
        if($(this).text() =='Read More'){
          $(this).text('Read Less');
        }
        else{
          $(this).text('Read More');
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle-container">
  <div class="first">
    <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:
    </p>
    <span class="dots">...</span>
  </div>
  <div class="showmore" style="display: none;">
   <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>
  </div>
  <button type="button" class="read btn btn-info btn-xs">Read More</button>
</div>

<div class="toggle-container">
  <div class="first">
    <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:
    </p>
    <span class="dots">...</span>
  </div>
  <div class="showmore" style="display: none;">
   <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>
  </div>
  <button type="button" class="read btn btn-info btn-xs">Read More</button>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ionic: Error - Unable to access the 'ready' property of an undefined object

I keep encountering this error message: TypeError: Cannot read property 'ready' of undefined Here is the snippet of my code: angular.module('app', ['ionic', 'app.controllers', 'app.routes', 'app.dir ...

Explore the tree structure with AngularJS and populate it with data from a JSON

After utilizing the AngularJS TreeView example from this JSFiddle link, I encountered a peculiar issue. When attempting to retrieve data from a JSON file similar to the code provided, the tree structure appeared empty. Upon inspecting the $scope.roleList1 ...

Is it possible to make the mat-menu-item the same size as the mat-menu button in Angular Material v.12?

How can I ensure that the mat-menu-item button is the same size as the mat-menu itself? For example, click here <div class="container d-block d-md-none"> <div class="row"> <div class="col d-flex justify-content-cent ...

Using JQuery to target and select all the lists except for the final one in a group of multiple lists

Seeking advice on the most elegant and efficient approach for my task. I am working with multiple 'tag' lists and aiming to make them display inline and comma-separated through CSS. The main challenge I face is adding commas to all list items ex ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

Utilizing two distinct CSS frameworks within a single Rails application

At the moment, I have an application with its frontend built using Bootstrap 3 (leveraging the bootstrap-rails gem). Now, I am looking to incorporate the Materialize.css framework into the same app. After downloading the Materialize.css stylesheet, my conc ...

Can you explain the purpose of $winstonLoggerConfig<T>() and $winstonLogger<T>() in winston v3?

I'm currently using the winston logger and I want to implement flow typing for it. However, I am unsure of what exactly I should pass to it in order to achieve this. Below is my current logger setup: const logger = createLogger({ ... }); Missing typ ...

File bootstrap.min.css is currently experiencing compatibility issues

I am currently working on a website where I have two images that are displaying vertically. However, I would like these images to be displayed horizontally with animation. I attempted to use Bootstrap to achieve this horizontal layout, but when I include ...

What is the best way to locate and send a message to a particular channel within a server?

I've been working on a Discord bot using Discord.js and I'm currently attempting to create a welcome command. My goal is to send a message to a specific channel within my server. However, due to recent updates in discord.js, I'm having troub ...

Guide to removing a duplicate footer generated by a Rails application due to the use of .load in jQuery/AJAX

Currently, I am utilizing jQuery/AJAX to dynamically load a page within my rails application using the code snippet shown below: $("#div1").load(url); The challenge I am facing is that the loaded page contains its own footer. As a result, when this div i ...

What is the behavior of the JavaScript event loop when a Promise's resolution is tied to setTimeout?

console.log('1') setTimeout(() => { console.log('2') }, 0) function three() { return new Promise(resolve => { setTimeout(() => { return new Promise(resolve => resolve('3')) },0) ...

Using JavaScript to Retrieve, Manipulate, and Merge JSON Data from Various Files

My knowledge of JavaScript is limited, but I am interested in uploading multiple JSON files, processing them, converting them to text, combining them, and downloading them into a single JS file. I have successfully achieved this for a single file, but I a ...

Troubleshooting problem with Angular's ng-repeat directive in dealing with varying number of child objects

I am currently dealing with tree-structured data where the parent nodes can have an indefinite number of children, and those children can also have an indefinite number of children, creating a deeply nested structure. While I have successfully formatted th ...

Passing form data to PHP using AJAX in CodeIgniter Framework

I'm facing an issue with my HTML structure which is as follows: <form method="POST"> Name : <input id="asgname" type="text"> <br> Description : <input id="asgdescription" type="text"> <br> <a href="#" id=" ...

Converting JSON information into a mailto hyperlink

Can anyone help me figure out how to encode a mailto link properly with JSON data in the query parameters, ensuring that it works even if the JSON data contains spaces? Let's consider this basic example: var data = { "Test": "Property with spaces" ...

What's the best way to refresh append() functionality within a modal? I'm currently working with NODE JS and AJAX and

Whenever I click the modal, the append() calls are adding HTML content. But if I try to use empty() or html(), the modal stops appearing altogether. What is the correct approach to creating this modal? function loadModalContent(id) { $('#myModal& ...

"Obtaining a URL that begins with using jQuery: A Step-by-

How can I extract the full URL that starts with http://sin1.g.adnxs.com Here is the code snippet: <div id="testingurl"> <div class="ads98E6LYS20621080"> <!-- This script is dynamically generated --> <iframe src="http://testing ...

The image source failed to load the image using the function

Initially, I set up a sandbox to work on this issue: https://codesandbox.io/s/naughty-almeida-u66mlt?file=/src/App.js The main problem arises when the requested image fails to display after the function is called and the URL is returned. Here are my atte ...

Retrieving data from radio buttons using React Hook Form

As I delve into learning React and Next.js, working with form submissions has been a breeze thanks to react-hook-form. However, I've hit a roadblock when it comes to handling radio buttons in my application. Specifically, there's a step where use ...