Creating multiple "read more" and "read less" buttons on a single webpage

Can you figure out what's going wrong here? I assigned each one a separate ID, but it's still not functioning properly in my code. I need to get this fixed for an assignment that's due in a few days, so any help is appreciated!

function readMoreRome() { //function to expand text
    var dots = document.getElementById("dots"); //searches for element with ID attribute "dots"
    var moreText = document.getElementById("more"); //searches for element with ID "more"
    var btnText = document.getElementById("myBtn"); //searches for element with ID "myBtn"

    if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.innerHTML = "Read more"; //changes button text to "Read more"
        moreText.style.display = "none";
    } else {
        dots.style.display = "none";
        btnText.innerHTML = "Read less"; //changes button text to "Read less"
        moreText.style.display = "inline";
    }
}

function readMoreBuda() { //function for expanding text
    var dots = document.getElementById("dots2"); //searches for element with ID "dots2"
    var moreText = document.getElementById("more2"); //searches for element with ID "more2"
    var btnText = document.getElementById("myBtn2"); //searches for element with ID "myBtn2"

    if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.innerHTML = "Read more"; //changes button text to "Read more"
        moreText.style.display = "none";
    } else {
        dots.style.display = "none";
        btnText.innerHTML = "Read less"; //changes button text to "Read less"
        moreText.style.display = "inline";
    }
}
<div class="card">
    <h2>Visit Budapest</h2>
    <div class="info"> <span class="date"><i class="far fa-calendar"></i> November 12, 2019</span> <span class="comment"><i class="far fa-comment-alt"></i> 2 comments</span> </div>
    <div class="img"><img src="img/szechenyi.jpg" style="height:200px;"> </div>
    <p><i>Széchenyi Thermal Baths </i></p>
    <p>
        Budapest is the capital city of Hungary. It is best known for its arts and culture. It is a relatively small city, however there are much to see and do.
        <span id="dots2">...</span>
        <span id="more2">Situated on thermal springs, there are many naturally heated baths to relax in, the Széchenyi baths are the largest with 15 indoor baths and 3 outdoor. There are many spectacular viewpoints in Budapest, great for capturing the views of the city. From 360 panoramic views up at St Stephens Basilica to a wide view of the parliament and the River at Fisherman’s Bastion. Visit the Museum of Fine Arts and enjoy a day amongst famous European art. Classical music lovers will appreciate a performance at the Academy of Music.</span>
    </p>
    <button onclick="readMoreBuda()" id="myBtn2">Read more</button>
</div>
<br>
<div class="card">
    <h2>Visit Barcelona</h2>
    <div class="info"> <span class="date"><i class="far fa-calendar"></i> December 06, 2019</span> <span class="comment"><i class="far fa-comment-alt"></i> 5 comments</span> </div>
    <div class="img"><img src="img/guell-park.jpg" style="height:200px;"></div>
    <p><i>Park Güell </i></p>
    <p>
        Barcelona, known for its unique culture, art, and architecture. Facing the Mediterranean to the southeast,
        <span id="dots3">...</span>
        <span id="more3"> the city is one of a kind. When visiting, be sure to explore the spectacular and unique Park Güell, designed by artist Antoni Gaudí. Gaudí's work is admired worldwide for its unique and distinctive style. Other must-see places in Barcelona include La Sagrada Família, a monumental basilica. With beaches, art, and city culture, Barcelona has a lot to offer.</span>
    </p>
    <button onclick="readMoreBarca()" id="myBtn3">Read more</button>
</div>

I'm having some trouble with the buttons here - the first one works fine, but the second one doesn't seem to be responding. I even changed the ID, but it's still giving me issues. It seems to work after clicking it multiple times, which isn't ideal. Can anyone help with this?

Answer №1

It appears that you have not defined readMoreBarca()... Instead, you have defined readMoreRome(), but it is never utilized.

There is code duplication present, which is generally considered a bad practice. It would be better to have a parameterized function like the following:

function readMore(city) {
    let dots = document.querySelector(`.card[data-city="${city}"] .dots`);
    let moreText = document.querySelector(`.card[data-city="${city}"] .more`); 
    let btnText = document.querySelector(`.card[data-city="${city}"] .myBtn`);

    if (dots.style.display === "none") {
        dots.style.display = "inline";
        btnText.textContent = "Read more";
        moreText.style.display = "none";
    } else {
        dots.style.display = "none";
        btnText.textContent = "Read less"; 
        moreText.style.display = "inline";
    }
}
<div class="card" data-city="buda">
    <h2>Visit Budapest</h2>
    <div class="info"> <span class="date"><i class="far fa-calendar"></i> November 12, 2019</span> <span class="comment"><i class="far fa-comment-alt"></i> 2 comments</span> </div>
    <div class="img"><img src="img/szechenyi.jpg" style="height:200px;"> </div>
    <p><i>Széchenyi Thermal Baths </i></p>
    <p>
        Budapest is the capital city of Hungary. It is best known for its arts and culture. It is a relatively small city, however there are much to see and do.
        <span class="dots">...</span>
        <span class="more" style="display: none;">Situated on thermal springs, there are many naturally heated baths to relax in, the Széchenyi baths are the largest with 15 indoor baths and 3 outdoor. There are many spectac...	glUniform(state, `')proof-of-work'");
    }
}

Answer №2

For those seeking a clearer example based on the code above, here is an illustration:

`<!DOCTYPE html>
 <html lang="en">
 <head>
 <meta charset="UTF-8" />
 <title> Show More/Less </title>

 <style>
 .j { width: 30em; text-align: justify; }
 .hide { display: none; }
 .pink { background-color: tan;  color: white; }
 b, span { cursor: pointer; }
</style>

</head>
<body>
<p class="j">Budapest, the capital city of Hungary, is renowned for its rich arts and culture scene. Despite its size, the city offers a plethora of attractions to explore.

 <b class="pink" onclick="evtEllipse(this)">&hellip;</b>

 <span class="hide" onclick="spanEllipse(this)">
The city is home to unique thermal springs, including the Széchenyi baths, offering a relaxing experience. Budapest also boasts breathtaking viewpoints, such as St Stephen's Basilica and Fisherman's Bastion, perfect for capturing the beauty of the city. Visitors can immerse themselves in the Museum of Fine Arts and enjoy classical music performances at the Academy of Music.
</span>
</p>

<p class="j">
Barcelona, known for its distinctive culture, art, and architectural wonders, is a captivating city with a Mediterranean backdrop.

 <b class="pink" onclick="evtEllipse(this)">&hellip;</b>

 <span class="hide" onclick="spanEllipse(this)">
Noteworthy attractions in Barcelona include Park Güell, designed by Antoni Gaudí, and the iconic La Sagrada Família basilica. With its blend of beachfront relaxation, art, and vibrant city life, Barcelona offers a diverse range of experiences.
 </span>
</p>

<script>
// For: http://www.webdeveloper.com/forum/showthread.php?364215-Show-only-first-line-of-a-paragraph&p=1508263#post1508263
function evtEllipse(info) {
  info.nextElementSibling.classList.toggle('hide');
  info.classList.toggle('hide');
}
function spanEllipse(info) {
  info.classList.toggle('hide');
  info.previousElementSibling.classList.toggle('hide')
}
</script>
</body>
</html>
`

Answer №3

If you're looking for an alternative solution to your issue, consider the following approach: There are 3 methods available for display - initText(), initWords(), and initLines(). Feel free to select the one that best fits your needs and eliminate the others as required.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> Ellipse </title>

<style>
 .j { width: 30em; text-align: justify; }
 .hide { display: none; }
 .pink { background-color: tan;  color: white; }
 b, span { cursor: pointer; }
</style>

</head>
...

Answer №4

Explore this code snippet and technique on how to implement - use a variety of methods to achieve the desired outcome

function readMoreFun(param, param_id) {
  let elements = document.getElementsByClassName(param);
  let element_id = document.getElementById(param_id);
  for (let i = 0; i < elements.length; i++) {
    elements[i].classList.toggle("hidden-content");
  }
  element_id.classList.toggle("hidden-readmore");
}
.container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  width: 80%;
  margin: auto;
  background: #f5f5f5;
  padding: 20px 40px;
}

.item h3 {
  font-size: 22px;
  font-family: Cambria, Cochin, Georgia, Times, "Times New Roman", serif;
  color: #813131;
}

.item p {
  font-family: "Trebuchet MS", "Lucida Sans Unicode", "Lucida Grande",
    "Lucida Sans", Arial, sans-serif;
  line-height: 1.3;
  font-weight: 300;
  font-size: 16px;
  word-spacing: 1.6px;
}

.hidden-content {
  display: none;
}

.read_more {
  color: #61b1f1;
  text-decoration: none;
  font-size: 20px;
  cursor: pointer;
}

.read_more:hover {
  color: #488ad6;
}
.hidden-readmore {
  display: none;
}
.read_less {
  color: #0f60bd;
  text-decoration: none;
  font-size: 20px;
  cursor: pointer;
}
<div class="container">

  <div class="item">
    <h3>Understanding Gravity?</h3>
    <p>Gravity is a force of nature that attracts objects with mass towards each other. It is one of the fundamental forces of the universe, alongside electromagnetism, strong nuclear force, and weak nuclear force. Sir Isaac Newton first described gravity in the late 17th century, and it was further developed by Albert Einstein's theory of general relativity in the early 20th century.<a id="read_more_1" onclick="readMoreFun('hide_seek-1',this.id)" class="read_more">...Read More</a></p>
    <div class="hide_seek-1 hidden-content">
      <p>Mass Attraction: Gravity pulls all objects with mass towards each other. The larger an object's mass, the stronger its gravitational force. This is why planets, stars, and other celestial bodies have powerful gravitational fields.</p>
      <p>Newton's Law: Gravity follows an inverse square law, where the force between two objects is proportional to their masses and inversely proportional to the square of the distance between them.</p>
      <p>Gravity Acceleration: Objects near Earth's surface experience a gravitational acceleration of approximately 9.81 meters per second squared. This means their speed increases by 9.81 meters per second for each second of free fall.<a onclick="readMoreFun('hide_seek-1','read_more_1')" class="read_less">...Read Less</a></p>
    </div>
  </div>

  <!-- Additional item examples for Gravity explanation -->

</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

Issue with static resource fetching when referencing a .js file within an HTML document while using Flask

My HTML file loads my OpenLayers JavaScript file (which displays a map frame) when opened directly. However, when running the HTML from my Flask python app, the JavaScript file/object fails to load (resulting in no map display, just some heading text). I ...

Storing css data for iPhone Facebook application

Currently, I am in the process of developing a webpage specifically for the iPhone Facebook app wall link. Interestingly, when attempting to apply the margin attribute to a div within the webpage, the margin doesn't seem to have any effect when clicki ...

Images cannot be uploaded using ajax

I have been troubleshooting an issue with uploading image files using ajax without refreshing the page. However, I am facing a problem where the file does not get moved to the specified folder even after implementing basic PHP code for file upload. if($_S ...

Developing connections using text phrases

Within my database, I have tags assigned to a particular item, separated by commas. For instance, the tags for a person could look like this: $tags = "tall, fun, cool"; My goal is to turn each word into a link while removing the commas. Currently, I&ap ...

Split an array into its individual elements and append key values to each element

I have a unique situation where I am working with a specific string format. The string I have is: IT, MEDIA, ADVERTISING To handle this scenario, I wrote the following code snippet. $criteria = explode(",", $string); When I use print_r to check the ...

MaxwidthLG in Material UI design

Hi there, I've encountered an issue with Material UI CSS. Even after attempting to override it, the desired effect is still not achieved. My goal is for the entire div to occupy the full page but this is the current result: https://i.stack.imgur.com/b ...

What is the quickest method for retrieving li data using selenium?

Greetings! Your attention to this post is greatly appreciated. I recently set out to gather insights on a particular news article. Out of the staggering 11,000 comments attached to the news piece, I was able to acquire data from approximately 6,000 commen ...

Is there a way to get a Chrome extension to run automatically in the background?

I am looking to develop a custom chrome extension with a countdown timer functionality that automatically runs in the background. However, I am facing an issue where my background.js file is unable to access the popup.html file. How can I execute scripts i ...

Error: The property 'rtl' is not defined and cannot be read

I'm currently in the process of developing a vuejs component library that utilizes vuetify 2.1.4 and attempting to import it into another application locally through npm link. However, I'm encountering numerous errors such as TypeError: Cannot ...

Stop Form Submission in Bootstrap 5

I require assistance with identifying the issue in the JavaScript code provided below. I am working with a Bootstrap 5 form where the submission is not being prevented if the fields are left blank or invalid. While the HTML/CSS validation works correctly f ...

The functionality of this.clusterer is not defined when trying to add a marker using this.clusterer.addMarker(marker);

I'm encountering an error message that says this.clusterer is undefined. Below is an overview of my configuration. Expected behavior: The page should load, then AJAX-load the markers from the controller using the query defined in #search_form. Finall ...

Tips for adding a value at a specific index in an array and moving all other elements down by one index

Suppose I have an array in VBA like this a(0) = 1 a(1) = f a(2) = g a(3) = 4 . .. .. a(k) = a and I need to add a new value at index (0) and shift every other value down by one index as shown below a(0) = newVal a(1) = 1 a(2) = f a(3) = g a(4) = 4 . .. ...

Managing and displaying information provided through forms

I'm currently developing a URL shortening tool, but I'm encountering difficulties in extracting jQuery form values to generate the shortened URL text. You can view the form layout here: <form name="urlForm"> <input type="text" name ...

Effortlessly initiate the consecutive playback on SoundCloud

I'm currently working on my music blog and I'm looking for some guidance in implementing a feature where the widgets start playing one after the other. Specifically, I have both SoundCloud and YouTube widgets, but I would like to focus on achievi ...

Can an older style class be inherited from an ECMAScript 6 class in JavaScript?

When I run the code below on Node.js version 4.2.1: 'use strict'; var util = require('util'); class MyClass { constructor(name) { this.name = name; } } function MyDerived() { MyClass.call(this, 'MyDerived'); } ...

Color key in square shape for graph legend

I am looking for legend colors in square shape, but I don't want them to appear as square boxes on the graph. https://i.stack.imgur.com/Of0AM.png The squares are also showing up on the graph, which is not what I want. https://i.stack.imgur.com/Az9G ...

Divs should be of consistent and adjustable height

I am in need of a layout with three columns: left column (with a red background) center column (with a yellow background) right column (with a black background) This is the HTML structure I have in mind: <div id="container"> <div id="left_ ...

Node.js MySQL REST API query fails to execute

I am developing a login/sign up API using nodejs, express, and mysql. Despite receiving the "Successful Sign Up!" message without any errors during testing, the user table in the database remains empty. Below is the query I am attempting to execute: con. ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

Incorporate additional form element functionalities using radio inputs

Recently, I created code that allows a user to duplicate form elements and add values by clicking on "add more". Everything is functioning properly except for the radio inputs. I am currently stuck on this issue. Does anyone have any suggestions on how I c ...