The "Read more" button is displaying inaccurate data

I have a problem with the read more buttons under my testimonials on the page.

The left button is working correctly, but the right button is displaying text from the wrong testimonial.

I'm not sure why this is happening as there are no console errors.

You can see the issue by visiting clientsforcounsellors.com and scrolling down to view the testimonials.

Here is the code for the left testimonial:

<!-- Quotation -->
                <p class="test-paragraph dark-grey-text mt-4"><i class="fas fa-quote-left pr-2"></i>"Harrison has been continually knowledgeable, patient, professional, and overall a fantastic help. He is clearly well informed in the digital marketing and web design field.<span class="dots">...</span><span class="read-more"> He always gives timely responses which are clear and helpful. The finished site looks professional and inviting – just what I wanted. I will recommend him to my colleagues. Thanks again, Harri."</span></p>

                <button onclick="readMore()" class="read-more-btn">Read More</button>

And here is the code for the right testimonial:

<p class="test-paragraph dark-grey-text mt-4"><i class="fas fa-quote-left pr-2"></i>"Harrison has been continually knowledgeable, patient, professional, and overall a fantastic help. He is clearly well informed in the digital marketing and web design field.<span class="dots">...</span><span class="read-more"> He always gives timely responses which are clear and helpful. The finished site looks professional and inviting – just what I wanted. I will recommend him to my colleagues. Thanks again, Harri."</span></p>

                <button onclick="readMore()" class="read-more-btn">Read More</button>
.read-more {
    display: none;
}
<script>

        var testParagraph = document.querySelectorAll(".test-paragraph");
        var i;
    
        for (i = 0; i < testParagraph.length; i++) {

          function readMore() {

          var dots = document.querySelector(".dots");
          var moreText = document.querySelector(".read-more");
          var btnText = document.querySelector(".read-more-btn");

          if (dots.style.display === "none") {
              dots.style.display = "inline";
              btnText.innerHTML = "Read More";
              moreText.style.display = "none";
          } else {
              dots.style.display = "none";
              btnText.innerHTML = "Read Less";
              moreText.style.display = "inline";
            }
          }
        }

      </script>

Answer №1

you have the option to utilize a

const seeMore = () => {
  const button = event.target;
  const para = button.previousElementSibling;

  const dots = para.querySelector(".dots");
  const moreContent = para.querySelector(".see-more");

  if (dots.style.display === "hidden") {
    dots.style.display = "inline";
    button.innerText = "Show More";
    moreContent.style.display = "none";
  } else {
    dots.style.display = "hidden";
    button.innerText = "Show Less";
    moreContent.style.display = "inline";
  }
}
.see-more {
  display: none;
}
<!-- Quotation -->
<p class="custom-paragraph grey-text mt-4"><i class="fas fa-quote-left pr-2"></i>"Harrison has been continually knowledgeable, patient, professional, and overall a fantastic help. He is clearly well informed in the digital marketing and web design field.<span class="dots">...</span><span class="see-more"> He always gives timely responses which are clear and helpful. The finished site looks professional and inviting – just what I wanted. I will recommend him to my colleagues. Thanks again, Harri."</span></p>
<button onclick="seeMore()" class="see-more-btn">Show More</button>


<p class="custom-paragraph grey-text mt-4"><i class="fas fa-quote-left pr-2"></i>"Harrison has been continually knowledgeable, patient, professional, and overall a fantastic help. He is clearly well informed in the digital marketing and web design field.<span class="dots">...</span><span class="see-more"> He always gives timely responses which are clear and helpful. The finished site looks professional and inviting – just what I wanted. I will recommend him to my colleagues. Thanks again, Harri."</span></p>
<button onclick="seeMore()" class="see-more-btn">Show More</button>

preceding element resembling this.

Answer №2

In my experience, I would advise against declaring JavaScript events directly inside HTML tags like this:

<button onclick="readMore()"...

Instead, a better approach would be to utilize the forEach() method and the toggle() method for toggling the read-more class. Take a look at the revised code snippet below.

var btnText = document.querySelectorAll(".read-more-btn");
var moreText = document.querySelectorAll(".read-more");
var dots = document.querySelectorAll(".dots");

btnText.forEach(function(current_btn, index) {
    current_btn.addEventListener('click', function() {
      moreText[index].classList.toggle("read-more");
      
      if (dots[index].style.display == "none") {
        dots[index].style.display = "inline";
      } else {
        dots[index].style.display = "none";
      }

      if (current_btn.innerText == "Read More") {
        current_btn.innerText = "Read Less";
      } else {
        current_btn.innerText = "Read More";
      }
            
    });
});
.read-more {
    display: none;
}
<p class="test-paragraph dark-grey-text mt-4"><i class="fas fa-quote-left pr-2"></i>"Harrison has been continually
    knowledgeable, patient, professional, and overall a fantastic help. He is clearly well informed in the digital
    marketing and web design field.<span class="dots">...</span><span class="read-more"> He always gives timely
        responses which are clear and helpful. The finished site looks professional and inviting – just what I wanted. I
        will recommend him to my colleagues. Thanks again, Harri."</span></p>
<button class="read-more-btn">Read More</button>

<p class="test-paragraph dark-grey-text mt-4"><i class="fas fa-quote-left pr-2"></i>"Harrison has been continually
    knowledgeable, patient, professional, and overall a fantastic help. He is clearly well informed in the digital
    marketing and web design field.<span class="dots">...</span><span class="read-more"> He always gives timely
        responses which are clear and helpful. The finished site looks professional and inviting – just what I wanted. I
        will recommend him to my colleagues. Thanks again, Harri."</span></p>
<button class="read-more-btn">Read More</button>

Answer №3

querySelector selects only a single element even if there are multiple elements present. This is in contrast to getElementsByClassName which retrieves all elements and stores them in an array. Therefore, when using querySelector, only one element will be selected:

 var dots = document.querySelector(".dots"); // selects one .dots element from multiple .dots elements
 var moreText = document.querySelector(".read-more"); // selects one .read-more element from the class
 var btnText = document.querySelector(".read-more-btn"); // selects one .read-more-btn from the class

As a result, when the readMore() function is called, it chooses the first of the two elements (Gloria between Gloria and Tommy).

To target both elements within a for loop, utilizing getElementsByClassName or querySelectorAll would be beneficial.

        for (i = 0; i < testParagraph.length; i++) {

          function readMore() {

            var dots = document.querySelectorAll(".dots")[i];
            var moreText = document.querySelectorAll(".read-more")[i];
            var btnText = document.querySelectorAll(".read-more-btn")[i];

... 
}

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

Is it possible to create a mouse-following effect with lighting using Javascript

Recently, I've been honing my Javascript skills and decided to create a follow-mouse function. After successfully implementing it, I started brainstorming a new concept that I'm unsure is achievable. Is there a way to develop an "orb of vision" ...

Issue adding dictionary value to an array in JavaScript

Let's analyze the code snippet below: var array = []; var obj = [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}] for (x in obj){ array.push(x.name) } After running this code, the array ends up with the correct length but ...

The body content of the webpage needs to be updated without altering the header and footer, all while avoiding a page

On my website, I have a header menu that includes buttons for "home" and "about us." The default page is set to the home page. Within the home page, there is a specific link. When this link on the home page or the "about us" button is clicked, I want the ...

Slideshow development with code

This is the code I currently have: HTML: <head> <title>JQuery demo</title> <script type="text/javascript" src="scripts/jQuery.js"></script> <script type="text/javascript" src="scripts/slider.js"></script ...

Navigating to a specific page based on the selected option is the key to efficient web browsing

I'm currently working on a form development project and I'm looking for guidance on how to navigate to different pages based on the selection made in a radio button. Here's the current form setup with two radio buttons: .sh_k .sh_sl { ...

Setting the ajax mock calls count to zero in Jest test suites

In my current testing setup, I have a test structure that involves using ajax calls and mocking them based on the Jest tutorial found here: describe('it behavior', function() { it('is as it is', function() { jQuery.ajax.mock.call ...

Styling with CSS in a React component

I am trying to display a row of buttons instead of columns on my webpage. I have used display:flex but it is still showing as a column. What I want is for each button to display the first character of its name underneath it, with all buttons lined up next ...

Shopping cart has encountered an issue with storing the data correctly

While I've managed to successfully integrate another service, the challenge now lies in implementing the logic for correctly generating cart items. My goal is to increment the quantity of items in the cart by one with each function call, but it seems ...

What are the steps to implement a horizontal scroll feature on a website when the scroll width is set to 0?

My goal is to enable users to scroll in the web view similar to how they can drag to scroll on mobile devices Check out my sandbox here for reference I have created a sample sandbox with the following code: <!DOCTYPE html> <html lang="en&qu ...

What is the best way to manage a custom child event that is triggered using this.$emit in a parent component, specifically within the <script> section of the .vue file?

In our project, we're utilizing vue and typescript, which means that our .vue files are structured very similarly to the layout outlined in this blogpost. One of our child components is emitting a custom event called changeType. I'd like to trig ...

Create a timestamp with Javascript rendering

Looking to convert a Unix timestamp into a human-readable format without adjusting for my browser's timezone. For example, if the timestamp is 1400167800 (05 / 15 / 14 @ 3:30:00pm UTC) and my timezone is +2, how can I display this timestamp as ' ...

Highlight the active link in the parent node changes color when the child node is in focus

I've designed a CSS vertical menu with the code provided below. You can view the test page at . The issue I'm facing is that when hovering over the sub-menu items, the highlighted 'li' in the parent node reverts back to the non-hover c ...

Tips for creating a full-screen background image using HTML and CSS

I am looking to achieve a full-screen background image using HTML and CSS. I have configured all the necessary properties for the background image. Here is where my background image is located: [![enter image description here][1]][1] I have attempted to ...

The function 'find' cannot be invoked on an undefined object

I'm currently working on implementing objects in my jQuery code. So far, I have the following: var options = { ul: $(this).find('.carousel'), li: options.ul.find('li') } The li property is causing an error - Cannot call meth ...

Utilizing the Twitter API with Next.js to automate tweets even when the website is not actively engaged

Currently, I am utilizing next.js for the development of a web application. My goal is to have this app automatically post to my Twitter account. I have already set up a developer account on Twitter and an API in nextjs. By calling the API, it will trigger ...

Encountering the "No injector found for element argument to getTestability" error while navigating between various single page applications

Currently, I am conducting tests on Protractor for a website that is bootstrapping AngularJS manually. Despite the steps continuing to execute, I encounter this error: Error while waiting for Protractor to sync with the page: "[ng:test] no injector found ...

The placeholder attribute for input types does not display consistently across all browsers

I am experiencing an issue with the placeholder text in my input field. <input type="text" name='linkLabel{{index}}' autocomplete="off" class="input-large tight-form-url last remove-cross" required="required" placeholder="{{'linkLabel&ap ...

Tips for resuming a video playback in HTML5 after pausing it for a brief moment

I am working with a video called introVid, and my goal is for it to pause for 2 seconds when it reaches the 1 second mark before resuming playback. Although I've attempted to achieve this using the code below, the video remains in a paused state after ...

Discover the magic of retrieving element background images on click using jQuery

I am attempting to extract the value for style, as well as the values inside this tag for background-image. Here is the script I have tried: function getImageUrl(id){ var imageUrl = jQuery("."+id+". cycle-slide").attr("src"); alert('' + ima ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...