0

I use a function in Jquery to replace the content of a h1 and to expand (or contract if it's already extanded) the content under the h1.

The way I call my jquery function is simply using $( "h1" ).click(function(){}.

My problem is that once my function has been called once I want to be able to call the function again in order to contract the content under the h1 and also to change back the content of h1, but when I click on the h1 it's not calling the function anymore although it's still a h1 element.

//call the function when h1 is clicked
$("h1").click(function() {

  //get the content of <h1> clicked except the first character
  ceci = (this.textContent).substring(1);

  $(this).next().slideToggle("slow", function() {
    //expand the div under h1
  });

  //replace the h1 content with a "-" instead of a "+"
  $(this).replaceWith("<h1> -" + ceci + "</h1>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>+ Présentation</h1>

<div id="presentation">
  Content initially invisible that is expanded once the function is called
</div>

I don't know why the function can't be called after the content of h1 has been changed although it's still a h1 element.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Ailiganon
  • 21
  • 1
  • 2
  • `$("h1").click` only applies to elements that exist at the time it runs. When you do `$("h1").replace(...` you *delete* that element and replace it with a different element, that's still an h1. You need to use event delegation: `$(document).on("click", "h1", function() { ...` – freedomn-m Dec 10 '21 at 16:18
  • As [now deleted comment], it would be better to use `.text()` or `.html()` to replace the content rather than the whole h1. Then you don't need event delegation. – freedomn-m Dec 10 '21 at 16:26

0 Answers0