How can I close the div also with the buttons inside it?
I manage to do it, but only with a button and I am interested in closing it with any of those inside:
function openFunctions() {
var div = document.getElementById("functions");
div.classList.toggle("block");
}
#functions{
margin-top: 20px;
background-color: #eee;
display: none;
}
#functions button{
display: block;
}
.block{
display: block !important;
}
<button onclick="openFunctions()">Abrir y cerrar</button>
<div id="functions">
<button>Funcion 1</button>
<button>Funcion 2</button>
<button>Funcion 3</button>
</div>
You can do what you want by adding to the click event of all the buttons a call to your function like so:
I've made use of
querySelectorAll()
to find all the buttons we want to add the function to. If you want to add it only to the buttons below it#functions
then the selector would be, for example,#functions button
.With
Array.forEach()
iterate one by one the results of the search carried out.The method
addEventListener()
adds a call to the specified function when the event of the first parameter is raised.In the case of buttons, the event
click
is the first parameter and the second is the name of the function that we have previously created.In the case of
document
waiting for the eventDOMContentLoaded
and in this case, instead of providing the name of a function as the second parameter, I generate it inline using the reduced function format by indicating(parámetros) => {contenido de la función}
.