Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!