Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Display div to none when button is clicked

I'm new at ES6 and I'm trying to display to none a div when an inner button is clicked.

I tried this but it's not working:

const hide = () => {
  const z = document.getElementById('button')
  const y = document.getElementById('block')
  z.onclick = () => {
    y.style.display='none'
  }
}
<div id="block">
  <button id="button" onClick="hide()">my button</button>
</div>

Any help please?

like image 446
BeeLee Avatar asked Mar 08 '23 14:03

BeeLee


2 Answers

You are attaching an event handler for first time. After the second time it will work and will again attach an event handler.

You don't need to use inline event handler, avoid this type of event handler attachement. You can just remove the hide function part serving the content. When your code runs, it will attach the event handler

const z = document.getElementById('button');
const y = document.getElementById('block');

z.onclick = () => {
    y.style.display = 'none';
};
<div id="block">
  <button id="button">my button</button>
</div>
like image 170
Suren Srapyan Avatar answered Mar 21 '23 06:03

Suren Srapyan


Instead of hiding the div, your hide method is assigning a new onclick handler to your button.

Simply

const hide = () => {
    document.getElementById('block').style.display='none'
  }
like image 41
gurvinder372 Avatar answered Mar 21 '23 07:03

gurvinder372