0

I'm trying to make text appear and disappear by clicking on the '+' but I can't seem to make it work. When I apply it to other sections the first one does not work anymore?

I'd prefer to set a max height to the appearing text so you can scroll to read everything but I don't know how and if it's possible the '+' should turn 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>

5
  • 1
    "When I apply it to other sections the first one does not work anymore?" Unclear what you mean with that statement, maybe you should show that problem. Commented Mar 3, 2020 at 15:38
  • @epascarello I have different 'sections' which i want to hide/unhide. When I apply the javascript code to all of them, they don't work properly anymore. I hope this helps Commented Mar 3, 2020 at 15:41
  • 1
    well ids are singular so that would be a problem.... Commented Mar 3, 2020 at 15:41
  • I understand, can I do this with classes? I'd like the same action to happen with different sections Commented Mar 3, 2020 at 15:43
  • Please note that you should use a <button>, not an <h5>, for the interactive element. Commented Mar 10, 2020 at 20:40

2 Answers 2

1

Like this - selecting each h5

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>

Sign up to request clarification or add additional context in comments.

7 Comments

It works here, so you must have a difference, for example I moved the + to before the text. If you want it after change nextElementSibling to previousElementSibling
Could you have a look on the website? I updated it with your code
@JanClerinx what site?
severinereard.be/test
I changed the script. Please copy the new script
|
0

Change the function to:

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

Change the #hide to .hide:

.hide {
    display: none;
}

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

And add the event parameter:

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

4 Comments

OP says "When I apply it to other sections the first one does not work anymore" so using an id is part of the problem, since an id can apply to only one element.
Thanks @StephenP, I have edited the answer to work in different sections. What it does now is checking the parent element and look for its p child and work with that.
If the h and ps are all in the same section, your code will only ever show the first p
I am trying to solve the current problem he posted. If you want to have a lot of ps and hs in the same section, just asign a different id to each one and pass that id as parameter to the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.