Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to toggle the appearance of content on clicking on a paragraph jQuery

I want some html content to appear when clicking on the text, such as a button or an input, and on second click, its disappear

<p class="test">test</p>
<script
    src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"
    integrity="sha512-pumBsjNRGGqkPzKHndZMaAG+bir374sORyzM3uulLV14lN5LyykqNk8eEeUlUkB3U0M4FApyaHraT65ihJhDpQ=="
    crossorigin="anonymous"
    referrerpolicy="no-referrer"
></script>
<script>
var toggle = 0;

$( "p" ).click(function() {
    var htmlorig = $( this ).html();
    if (toggle != 1) {
        var toggle = 1;
        $( this ).html( htmlorig + '<button>sds</button>' );
      } else {
        var toggle = 0;
        $( this ).html( htmlorig );
      }
});
</script>

Here is codepen https://codepen.io/pire-code/pen/QWZyVZE

I tried this, didn’t work.
I am aware that I can use another cdn.
Help, please.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can store the original HTML and the toggle variable inside a closure with .each.

$('p').each(function() {
  const $this = $(this);
  const htmlOrig = $this.html();
  let toggle = 1;
  $this.click(function(e) {
    $this.html(toggle ? htmlOrig + ' <button>sds</button>' : htmlOrig);
    toggle ^= 1;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="test">test</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading