skip to Main Content

I am new to code so appreciate if anyone could help.

But what I currently have is two buttons (button A and button B) to hide and show its corresponding divs (div A and div B). The divs appear taking up 50% of screen width and depending on the order they are clicked will determine their position. First click (regardless if its button A or button B) will appear 50% width right of screen and second click (again regardless if button A or button B) will appear 50% width left of screen.

So end result should appear something like this

Problem: However this is my code currently (below) and wish for the first click corresponding div to initially appear right of screen and second click corresponding div to appear left of screen, rather than second click moving the div to the right?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .columns{
            width:50%;
            height:100%;
        }
        body , html{
            height:100%;
        }
        span{
            margin-top:50%; margin-bottom:50%;
        }
        .columns div{
            position:relative;
            top:50%;
            color:white;
        }
    </style>
</head>
<body>
    <button class="buttons" data-id="buttonA">Button A</button>
    <button class="buttons" data-id="buttonB">Button B</button>

<div style="height:50%; display:flex;">
    <div class="columns" data-id="buttonA" style="background-color:green; text-align:center; position:relative; display:none;">
<div>div a</div>
    </div>
    <div class="columns" data-id="buttonB" style="background-color:red; text-align:center; position:relative; display:none;">
<div>div b</div>
    </div>
</div>
<script>
    let buttons=document.querySelectorAll('.buttons')
    for (let i = 0; i < buttons.length; i++) {
        
    
    buttons[i].addEventListener('click',function (params) {

        let button = params.target.getAttribute('data-id');
        let divs = document.querySelectorAll('.columns');
        for (let index = 0; index < divs.length; index++) {
            
            if (button==divs[index].getAttribute('data-id')){
                divs[index].style.display="Block"
                divs[index].after(divs[divs.length-1])
                if (divs[index].classList.contains('show')){
                divs[index].classList.remove('class','show');
                divs[index].style.display = "none"
                }
                else{
                divs[index].classList.add('show')
                divs[index].style.display="Block"
                }
            }else {
                divs[index].before(divs[divs.length-1])
            }
            
            
        }
    })
}
</script>
</body>
</html>

2

Answers


  1. Remove the style attribute from your divs as you’ll be applying styles using the CSS and JavaScript.

    Add a class (e.g., initial-right) to the divs that you want to initially appear on the right side of the screen.

    Add a variable to track the current position state of the divs.
    In the click event listener, toggle the class initial-right on the clicked div to control its initial position.
    Use CSS transitions to smoothly animate the transition between positions.

    Here’s the updated code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            .columns {
                width: 50%;
                height: 100%;
                transition: left 0.5s ease-in-out;
                position: absolute;
            }
            
            body, html {
                height: 100%;
                margin: 0;
            }
            
            .buttons {
                margin: 10px;
            }
            
            .initial-right {
                left: 50%; /* Initially right position */
            }
            
            .show {
                display: block !important;
            }
            
            .columns div {
                position: relative;
                top: 50%;
                transform: translateY(-50%);
                color: white;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <button class="buttons" data-id="buttonA">Button A</button>
        <button class="buttons" data-id="buttonB">Button B</button>
    
        <div style="height: 50%; display: flex;">
            <div class="columns initial-right" data-id="buttonA" style="background-color: green; display: none;">
                <div>div a</div>
            </div>
            <div class="columns" data-id="buttonB" style="background-color: red; display: none;">
                <div>div b</div>
            </div>
        </div>
    
        <script>
            let buttons = document.querySelectorAll('.buttons');
            let currentPosition = "right"; // Initial position
            
            for (let i = 0; i < buttons.length; i++) {
                buttons[i].addEventListener('click', function (params) {
                    let button = params.target.getAttribute('data-id');
                    let divs = document.querySelectorAll('.columns');
                    
                    for (let index = 0; index < divs.length; index++) {
                        if (button == divs[index].getAttribute('data-id')) {
                            divs[index].classList.toggle('initial-right', currentPosition === "right");
                            divs[index].classList.toggle('show');
                        }
                    }
                    
                    currentPosition = (currentPosition === "right") ? "left" : "right"; // Toggle position
                });
            }
        </script>
    </body>
    </html>
    
    Login or Signup to reply.
  2. There are probably many ways to do this, but one approach could be to use Map and Set in order to keep the references of the elements

    The Set visibleElements can help you know which element that is visible. And the Map elements holds the node references, so you can access the correct element by the id.

    Then you could attach a data attribute on the buttons in order to link a button to a specific div.

    Something that might be worth noting here is that when you remove a node from the DOM the reference of the node is still there, which allows you to append the same node again without creating new nodes etc each time (as long as you have access to the node reference).

    I’ll provide some code example here without styling, hope some of this makes sense for you 🙂

    <div id="root">
        <div class="element" id="div1">Div 1</div>
        <div class="element" id="div2">Div 2</div>
    </div>
    
    <div>
        <button data-toggle="div1">Show 1</button>
        <button data-toggle="div2">Show 2</button>
    </div>
    
    <script>
        const root = document.getElementById("root");
        const visibleElements = new Set();
        const elements = new Map();
    
        document.querySelectorAll('.element').forEach((element) => {
            const {id} = element; // Gets the id of the element
            elements.set(id, element); // Saves a reference of the element to the Map
    
            // If you want to have none visible at the initial state
            element.remove(); // Removes the element from the DOM
        });
    
        const handleToggle = (e) => {
            const {toggle: id} = e.target.dataset; // Gets the data-toggle value as "id"
            const element = elements.get(id); // Gets the element reference from the Map by the "id"
            
            if (visibleElements.has(id)) {
                element.remove(); // Removes the visible element from the DOM
                visibleElements.delete(id); // Removes it from the visibleElements Set
            } else {
                root.appendChild(element); // Inserts the element to the root / container
                visibleElements.add(id); // Adds the id to the visibleElements Set
            }
        }
    
        document.querySelectorAll("button").forEach((button) => {
            button.addEventListener("click", handleToggle)
        })
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search