Yyuv Ali
Yyuv Ali

Reputation: 7

make a text disapear and apear back at every button click

I have a button element and and paragraph element I attached the button element an eventListener (click)event so what I want is that when I click the button the paragraph's text disapears and when I click it again the same click I want it to appear back switching back and forth click disapear click disapear.

let button = document.querySelector("button");
button.addEventListener("click",function(e){

let p = document.querySelector("p");
p.style.display = "none";
this.addEventListener("click",function(c){
let p = document.querySelector("p");
p.style.display = "initial";
})
})

Upvotes: 0

Views: 53

Answers (2)

Andy
Andy

Reputation: 63550

You only need to add one event listener which toggles a class on/off.

const button = document.querySelector('button');
const p = document.querySelector('p');

button.addEventListener("click", handleClick, false);

function handleClick() {
  p.classList.toggle('hidden');
}
.hidden {
  display: none;
}
<button>Click</button>
<p>Hallo</p>

Upvotes: 3

Ori Drori
Ori Drori

Reputation: 192252

Use the original event handler, and change the value of p.style.display according to the current value of display:

const button = document.querySelector("button");
const p = document.querySelector("p");

button.addEventListener("click", function(e) {
  p.style.display = p.style.display === "none" ? 'initial' : 'none';

})
<p>Text</p>
<button type="button">Toggle</button>

Upvotes: 1

Related Questions