Search code examples
javascripthtmlcssbuttontoggle

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?


Solution

  • 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.