Conceal and reveal text using JavaScript

I am attempting to create a function where text appears and disappears when clicking on the '+' sign, but I am facing difficulties in getting it to work. Additionally, when I apply this function to other sections, the original one stops working altogether?

It would be ideal if I could set a maximum height for the appearing text so that users can scroll to read everything. Also, I am unsure if it's possible for the '+' sign to transform into an 'x' to close the text block.

function myFunction() {
  var x = document.getElementById("hide");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
#hide {
  display: none;
}
<section>
  <img src="img/trait8.svg"></img>
  <h3>Pelvi-p&eacute;rin&eacute;ologie</h3>
  <p id="hide">Tout d’abord qu’est-ce que la rééducation périnéale ou uro-gynécologie ? C’est un traitement qui consiste en la rééducation des muscles que comporte le plancher pelvien ou périnée. Il vise une prise de conscience par le patient ainsi qu’un renforcement
    ou relâchement (selon les pathologies) des muscles du périnée par un massage périnéal, biofeedback et l’électrostimulation. La rééducation pelvienne est très différente selon qu’il s’agisse d’une rééducation pour femmes, hommes ou enfants. La périnéologie
    cible les troubles liés à l’appareil urinaire (uro-gynécologie) et/ou anal (colo-proctologie) Rééducation périnéale chez les femmes Cette rééducation a lieu si il y a une instabilité vésicale (urgences mictionnelles), douleurs au rapports sexuels
    (dyspareunie), descente d’organe ou prolapsus ( cystocèle, rectocèle, hystrérocèle), incontinence urinaire (différents types) et/ou fécale. Ces troubles peuvent apparaitre à différents moments de la vie et les causes sont multiples ; pratique d’un
    sport a impact de manière intensive, suite a un accouchement ou au moment de la ménopause, … La rééducation se fait manuellement et avec une sonde vaginale pour permettre le biofeedback et/ou l’électrostimulation. Rééducation périnéale chez les enfants
    Si au-delà de cinq ans l’enfant fait encore pipi au lit (énurésie), si l’enfant perd de manière involontaire des émissions de selles du a un trop plein dans le rectum (encoprésie) ou si il souffre d’immaturité vésicale (incontinence urinaire le jour/nuit),
    la rééducation périnéale sera nécessaire. Chez les enfants on n’utilise pas de sondes mais de petites électrodes de surface. Rééducation périnéale chez les hommes Un homme peut également souffrir d’une instabilité vésicale, d’une faiblesse périnéale
    voir même d’incontinence urinaire/fécale. Cette rééducation trouve souvent lieu suite à une prostatectomie. Le patient peut alors après l’intervention chirurgicale souffrir d’incontinence urinaire. La rééducation se fait manuellement, avec une sonde
    anale pour permettre le biofeedback et/ou l’électrostimulation.
  </p>
  <h5 onclick="myFunction()">&plus;</h5>
</section>

Answer №1

Here is an example of how to target and modify each h5 element

window.addEventListener("load", function() {
  [...document.querySelectorAll("h5")].forEach(function(h5) {
    h5.addEventListener("click", function(e) {
      let show = this.innerText === "+"
      this.previousElementSibling.classList.toggle("show", show);
      this.innerText = show ? "x" : "+";
    })
  })
})
.hide {
  display: none;
}

.show {
  display: block;
}
<section>
  <img src="img/trait8.svg" />
  <h3>Pelvi-p&eacute;rin&eacute;ologie</h3>
  <p class="hide">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed facilisis lacus orci, id imperdiet nulla ultrices consequat. Aliquam imperdiet rhoncus mattis. Nam maximus feugiat felis, tempus vulputate lectus. Interdum et malesuada fames ac ante ipsum
    primis in faucibus. Nulla congue urna in arcu varius bibendum. Donec nec velit a justo auctor tincidunt. Nulla posuere augue at ipsum suscipit imperdiet. Proin a accumsan urna. Morbi nunc orci, maximus in pharetra in, blandit sed sem. Fusce ullamcorper
    nulla nunc, a hendrerit enim imperdiet ac. Nam feugiat nunc ut purus blandit, ac condimentum ante sagittis.</p>
  <h5>+</h5>
</section>
<section>
  <img src="img/trait8.svg" />
  <h3>Pelvi-p&eacute;rin&eacute;ologie</h3>

  <p class="hide">Curabitur sed lectus sed ante dictum sollicitudin. Aliquam volutpat condimentum laoreet. Curabitur sit amet fringilla purus. Cras maximus, nisl eget placerat dignissim, mauris sem ultricies orci, vitae tristique justo purus quis urna. In consectetur
    justo purus, id aliquam lectus scelerisque ac. Mauris bibendum pulvinar arcu, eu imperdiet ipsum vestibulum ut. Aliquam turpis augue, lacinia ac consequat id, ullamcorper at magna. Ut nec urna scelerisque, facilisis velit nec, feugiat lectus.</p>
  <h5>+</h5>

</section>

Answer №2

Revise the function as follows:

function updateDisplay(event) {
    var element = event.target.parentNode.getElementsByTagName("p")[0];
    if (element.style.display === "block") {
        event.srcElement.innerHTML = '+';
        element.style.display = "none";
    } else {
        event.srcElement.innerHTML = 'X';
        element.style.display = "block";
    }
}

Replace #hide with .hide:

.hide {
    display: none;
}

<p class="hide"></p>

Include the event parameter in the function:

<h5 onclick="updateDisplay(event)">&plus;</h5>

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

using database URL as an AJAX parameter

I am currently working on a Python CherryPy controller that needs to validate a database URL by attempting a connection. However, I am facing challenges with passing the parameter to the method. Below is my AJAX call: $.ajax({ async: false, ty ...

Is there a way to incorporate multiple plan tiers on Stripe's platform?

//api/stripe import { auth, currentUser } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; import { prismadb } from "@/lib/prismadb"; import { stripe } from "@/lib/stripe"; import { absoluteUr ...

PHP array is not displaying properly in two dimensions

Looking at the array of dates and places, I need to figure out how to properly format this information for display. Here is an example of what I am trying to achieve: 20140411 Basingstoke Salisbury 20140405 Basingstoke 20140419 Salisbury ...and ...

`Firefoxx border table glitch`

When attempting to open/close tables in Firefox using this link, unnecessary borders appear. https://i.sstatic.net/4tQCE.gif One way to fix this issue is by implementing the following JS solution: setTimeout(function () { $table.css({'table-la ...

Creating an interactive checkbox input field utilizing a JSON-driven database

Can someone assist me with creating dynamic checkboxes? I have JSON data structured as follows: [ { "categoryName": "Category 1", "items": [ { "value": "value1", "label": "label1" }, { "value": "value2" ...

methods for detaching event listener from bootstrap carousel indicator elements

I am currently utilizing the bootstrap5 carousel feature and I am seeking a way to trigger a custom event when either the previous or next indicators are clicked. My goal is to stop the default bootstrap event from being triggered, however my attempts at v ...

Steer clear of accessing cache data within web browsers

Is there a way to prevent the browser cache from affecting how I view a document? I would appreciate any help in solving this issue, whether it be through using JavaScript or another method. Thank you, Arun ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

Show the date and time in a visually appealing way by using HTML and JavaScript in an HTA application with scrolling effects

I have the following JavaScript code to show the current date in the format Mon Jun 2 17:54:28 UTC+0530 2014 within an HTA (HTML application). Now, I would like to display it as a welcoming message along with the current system date and time: Mon Jun 2 17: ...

What is the best way to manage a session using JavaScript?

Currently developing a website that initially hides all elements except for the password box upon loading. Once the user enters the correct password, all webpage elements are revealed. Seeking a solution to keep the elements visible on reload by utilizing ...

Musical backdrop for an online game platform

Currently, I am working on developing a game using HTML. I am trying to figure out the best way to incorporate music into the gameplay. Any suggestions on how I can add music to my web-based game? ...

Tips for setting React state using variables as keys or values

Although I managed to achieve the desired result, I'm still puzzled as to why my more straightforward approaches didn't work. Can someone help me understand what's going on here? Basically, I needed to set nested state at different levels u ...

Find the ultimate destination or URL provided by an ASP script

Hey there, I know this might not be the most popular question and I might even get kicked out for being a newbie asking silly questions that annoy people. But hey, I'm here because I think this community is pretty great. So here's the deal - I&a ...

Capture data from clipboard as it is being pasted into Handsontable

Issue Description and Troubleshooting: In a nutshell, I am seeking a method to manage data copied from the clipboard to a handsontable. I came across a suggestion on how to fetch this information using jQuery in a stackoverflow post: $("#haras_excel_li ...

Self-reference within a JavaScript object involves creating a property that points

Can you reference another part of a JSON object within the same JSON object? In the code snippet below, there is an object that refers to the "home" object within the "MapParameters" object. { "parameters": { "data": { "URL": "http://SC.json ...

combining elements in JavaScript

I have two object arrays that look like this: arr1 = [ { 'v1': 'abcde', 'pv_45': 13018, 'geolocation': '17.340291,76.842807' }] arr2 =[{ 'v1':'abcde', 'pv_50&apos ...

Updating the TextField in React Material UI based on the Slider value without affecting the Slider

Is there a way to update the value of a TextField based on the slider, while still allowing manual input in the TextField? I want the TextField to reflect changes from the slider but not vice versa. I attempted making the TextField a controlled component ...

Authenticating Users with HTML in Django

I am experiencing an issue with the following condition: {% if object.author == user or object.res_person_1_username == user %} When I display variables using code like this: <p class="article-content mb-1"><strong>object.res_person_ ...

What sets the screen property apart from the window property?

I'm working on a Web application and I need to access the browser window's Height & Width. Initially, I used JavaScript properties Screen.Width , Screen.Height to get these values. Later on, I came across another property called Window.Width , Wi ...

Activating Email Subscription Form by Clicking on Icon Image

I'm attempting to include an email submission form box that appears when users click on a small envelope icon located at the top right corner of my page. However, I've encountered some difficulty as it either shows up in the midst of other icons ...