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

How does the pound sign (#) signal the beginning of a comment in JavaScript?

I recently ran into an issue while trying to minify JavaScript using Grunt in my NPM project. The error thrown by Uglify was: Warning: Uglification failed. Unexpected character '#'. Line 1 in app/min-libs/node_modules/grunt-contrib-jshint/node_m ...

Ways to display tinyMCE content in a unique manner

I've been diving into node.js/express/mongoDB and decided to create a blog. I encountered an issue with rendering the content inputted through tinyMCE as HTML - instead, it's displaying the tags around my content. How can I properly display it as ...

Discovering the key to selecting a row by double-clicking in Vuetify's v-data-table

I'm having trouble retrieving the row by event in my v-data-table. It only gives me the event and remains undefeated. How can I catch items in the v-data-table? <v-data-table :headers="showHeaders" :page="page&quo ...

There seems to be an issue with Node.js/Express: the page at /

Recently, I've been working on some code (specifically in app.js on the server). console.log("Server started. If you're reading this then your computer is still alive."); //Just a test command to ensure everything is functioning correctly. var ...

Difficulty in transferring JavaScript variable to PHP

After encountering a basic issue, I learned that PHP runs server-side and executes on pageload even if the include is nestled in an AJAX callback. Initially, I could display query results by returning PHP in the JavaScript value attribute, but failing to i ...

Tips for boosting the efficiency of replaceWith on Internet Explorer 11

When rendering an array of data in a table element, there is a need for the table to be updated with new data as it can be filtered dynamically. However, I have encountered a performance issue specifically on IE11 when trying to render 1700 data entries us ...

How can PHP be used to display a varying number of items in a slider depending on the size of the screen?

I am currently utilizing media queries to adjust the layout of my website. My query is: How can I display a different number of items in a slider based on the screen size? For small screens, I have included the following code: <?php if($i == 4) {echo ...

Dynamic background image changes when checkbox is selected

Greetings! I am a newcomer to the stackoverflow community and I am facing an issue with dynamically changing the background image of my webpage when a checkbox is checked. Here is the HTML code snippet: <ul> <li><label for="Lines">A ...

Troubleshooting Problems with CSS Three-Column Layout

Struggling with aligning domain names in a 3 column setup, I have been attempting this for some time now without success. I am new to this and could use some guidance. Here is the code: TPL file <div> <p class="center">{foreach key=num it ...

Strategies for handling numerous node projects efficiently?

Currently, we are utilizing three distinct node projects: Project 1, Project 2, and Project 3 incorporating react and webpack. Each of these projects is stored in their individual repositories. While Project 1 and Project 2 operate independently, Project ...

What is the best way to distribute a function within a div container?

I'm currently working on a function that manages the show/hide functionality and position of tooltips: tooltip = (e) => { // show/hide and position of tooltip // retrieve element data } In addition, I have div elements whe ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

What is the best way to customize the style of a react.js component upon its creation?

Is there a way to set the style of a react.js component during its creation? Here is a snippet of my code (which I inherited and simplified for clarity) I want to be able to use my LogComponent to display different pages of a Log. However, in certain ins ...

How can you add draggable functionality to a Bootstrap dropdown menu?

My custom bootstrap dropdown design <div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> Dropdown <span cla ...

Avoiding the overflow of the y-axis by applying a slight left margin to bootstrap columns

Context: I'm in the process of developing a collapsible sidebar navigation menu inspired by the bootstrap admin panel example found at: Issue: Upon collapsing the admin bar, a small bar of icons appears. To accommodate this, I added margin-left: 50 ...

Wildcard GET requests in Express cause routing issues when navigating to a React application

My project is derived from the React-Webpack boilerplate repository found at this link: (https://github.com/wallacyyy/webpack-heroku/blob/master/server.js). Initially, everything was working fine but now I want to add routing within my React application. T ...

How to handle redirection in React when encountering a 404 error with React

Hey there, I'm encountering an issue related to react router. Let's take a look at my App.js file where all the routes are defined: const App = () => ( <div className="App"> <MediaQuery minWidth={700}> {(matches ...

Transforming a namespaced function into an asynchronous operation by utilizing setTimeout

Looking for help with making a function that uses namespaces asynchronous. The function is currently being called on the click of a button. var ns = { somemfunc: function (data) { alert("hello"); } } Edit: ...

Changing the position of an image can vary across different devices when using HTML5 Canvas

I am facing an issue with positioning a bomb image on a background city image in my project. The canvas width and height are set based on specific variables, which is causing the bomb image position to change on larger mobile screens or when zooming in. I ...

What is preventing this button from having a border-radius?

The red border is just for visual reference. I attempted using overflow: hidden but it didn't yield the desired outcome. My goal is to achieve the same border radius as the red border. Is there something amiss in my approach? Appreciate your assistanc ...