I have this little code in JS that shows or hides a div. I use it in three sections and the same thing happens in all three: I have to click twice to show the details for the first time. From there it works fine with a single click to both show and hide
<!DOCTYPE HTML>
<html lang="es">
<head>
<meta charset = "UTF-8">
<link rel="stylesheet" type="text/css" href="css/base.css" />
<link rel="stylesheet" type="text/css" href="css/menu.css" />
<link rel="stylesheet" type="text/css" href="css/presupuestos_ficha.css" />
<title>Título de la pagina</title>
<script>
function ver_detalles(seccion) {
if (document.getElementById(seccion).style.display === "none") {
document.getElementById("btn_"+seccion).innerHTML = "ocultar detalle";
document.getElementById(seccion).style.display = "block";
document.getElementById(seccion).style.visibility = "visible";
} else {
document.getElementById("btn_"+seccion).innerHTML = "mostrar detalle";
document.getElementById(seccion).style.display = "none";
document.getElementById(seccion).style.visibility = "hidden";
}
}
</script>
</head>
<body>
<h4>Desglose de gastos - <span id="btn_detalle_gastos" onclick="ver_detalles('detalle_gastos')">mostrar detalle</span></h4>
<div id="detalle_gastos"> <!-- este div se carga oculto y se muestra/oculta con la llamada a la función -->
<div>item 1: $ 32.90</div>
<div>item 2: $ 72000.00</div>
<div>item 3: $ 6950.00</div>
<div>item 4: $ 768.00</div>
<div>item 5: $ 500.00</div>
</div>
</body>
</html>
I have tested the function by placing it in different places on the page and the same thing always happens.
Well, considering what was mentioned in this comment:
An alternative solution could be to create two classes that serve as a "flag" to show or hide the detail as the case may be.
Here, I called the classes hidden and shown .
Since the use of inline events is discouraged , the function call has been moved to the click event , whose handler is added in the DOMContentLoaded event .
Likewise,
if
the function's view_details checks if the element contains the class hidden . If so, replace this class with shown . In theelse
, vice versa. The available method for classList was used : replace() , and to search for the class, the contains() method .You can use the event
ondblclick
, where this event occurs when the element is clicked 2 times:In your html:
I leave you an example overriding calling the function from the button, the best way is listening to the event and to avoid conflicts I add the event after finishing loading the DOM, with this you can put the script at the beginning or end of your page.
Tell me if it worked for you.
This is the code I ended up using:
All the answers helped me and I will adapt the code as suggested for inline events.
Thank you!