I Want to make a button to display a list of elements, and in the list, there is another button to close or display none of the lists but I don't know why it's not working
let btn1 = document.querySelector('#btn1');
let btn2 = document.querySelector('#btn2');
let article = document.querySelector('article');
btn1.addEventListener('click', (e) => {
article.style.display = 'flex';
})
btn2.addEventListener('click', (e) => {
article.style.display = 'none';
})
div {
position: relative;
width: 100px;
height: 100px;
background-color: white;
}
article {
position: absolute;
left: 100px;
display: none;
flex-direction: column;
}
p {
color: red;
}
span {
position: absolute;
right: -100px;
color: white;
}
<div id="btn1">
<article>
<p>hello world</p>
<p>hello world</p>
<p>hello world</p>
<span id="btn2">btn2</span>
</article>
</div>
strong text
There's a subtle thing happening in your scenario. The divs listening to the click event are nested so that the click event "bubbles" and gets propagated to the parent producing a scenario where both handlers get called for the same click -> hence your element is getting hidden and immediately after showed again.
To prevent that to happen I called event.stopPropagation() in the function handling the click event for the child element.
https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
let btn1 = document.querySelector('#btn1');
let btn2 = document.querySelector('#btn2');
let article = document.querySelector('article');
btn1.addEventListener('click', (e) => {
article.style.display = 'flex';
})
btn2.addEventListener('click', (e) => {
article.style.display = 'none';
event.stopPropagation();
})
div#btn1{
border: solid 1px red;
cursor: pointer;
}
div {
position: relative;
width: 100px;
height: 100px;
background-color: white;
border: solid 1px black;
}
article {
position: absolute;
left: 10px;
display: none;
flex-direction: column;
border: solid 1px black;
}
p {
color: red;
}
span {
position: absolute;
cursor: pointer;
/*
right: -100px;
color: white;*/
}
<div id="btn1">
<article>
<p>hello world</p>
<p>hello world</p>
<p>hello world</p>
<span id="btn2">Click Here</span>
</article>
</div>