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