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>
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?
Share Improve this question edited Nov 14, 2017 at 11:43 3Dos 3,4973 gold badges26 silver badges39 bronze badges asked Nov 14, 2017 at 11:15 BeeLeeBeeLee 1935 silver badges15 bronze badges2 Answers
Reset to default 5You 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>
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'
}