Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
Toggle between two divs using a button

Basically i have 2 divs on my HTML page, and i'm trying to create a function to toggle between the two, using the buttons on my HTML. One button would be to toggle to div 2, and the other would be to toggle back to div 1, just like the code below:

<button id="toggle-to-2">Toggle to div 2</button>
<button id="toggle-to-1">Toggle to div 1</button>

<div id="div-1">
This is div 1
</div>

<div id="div2">
This is div 2
</div>

Also, when using CSS, how should i position them? Should i give them the same position, and rely on the function to toggle between the two?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This is sort of primitive but it does what you want it to, I've tried my best to implement the best strategy for this toggle behavior which is tedious in vanilla JS compared to something like React.

const toggleTo2 = document.getElementById("toggle-to-2");
const toggleTo1 = document.getElementById("toggle-to-1");

const div1 = document.getElementById("div-1");
const div2 = document.getElementById("div2");

const hide = el => el.style.setProperty("display", "none");
const show = el => el.style.setProperty("display", "block");

hide(div2);
hide(toggleTo1);

toggleTo2.addEventListener("click", () => {
  hide(div1);
  hide(toggleTo2);
  show(toggleTo1);
  show(div2);
});

toggleTo1.addEventListener("click", () => {
  hide(div2);
  hide(toggleTo1);
  show(toggleTo2);
  show(div1);
});
<button id="toggle-to-2">Toggle to div 2</button>
<button id="toggle-to-1">Toggle to div 1</button>

<div id="div-1">
This is div 1
</div>

<div id="div2">
This is div 2
</div>

As for CSS, it's up to you but if they toggle I would assume you give them the same positioning.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda