The display and concealment of a div will shift positions based on the sequence in which its associated buttons are clicked

I am in need of assistance with coding (I am still learning, so please excuse any syntax errors).

What I am trying to achieve is having two buttons (button A and button B) that can toggle the visibility of their respective divs (div A and div B), which should function independently. These divs will each take up 50% of the screen width, and depending on the order in which they are clicked, their position should be determined. The first click (whether it's on button A or button B) should display the div 50% width from the right edge of the screen, while the second click (again, regardless of the button) will place the div 50% width from the left edge of the screen.

https://i.sstatic.net/KwGP5.png

I have managed to create a show and hide functionality for the divs, but I'm unsure how to control their positioning based on the order in which their corresponding buttons are clicked...

Answer №1

To streamline the button functionalities, I assigned a common class to both buttons for easy querying. Each button was then given a unique data-id attribute to distinguish between them. By setting up a click event listener on both buttons, I could capture the data-id of the clicked button and compare it with the columns. If there was a match, the corresponding div would be displayed and toggled based on its current visibility status.

<!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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Revise the if statement by using variables

Here is a function that already exists in a theme: function WShare( selector ) { var $this = $( selector ), $parent = $this.parent(); var opt = { url: window.location, text: document.title, }; if ( window.selectedText ) { ...

What is the process for extracting the differences between two or three files and merging them together in Node.js?

Recently, I've been experimenting with webpack and successfully managed to output and transform es5 build to include nomodule in the tags directly from HtmlWebpackPlugin using hooks. Similarly, for the es6 build, I added type="module". Howe ...

In what situations should the `#` symbol be used to select a DOM element?

There are times when I have to retrieve elements in the following ways: var object = document.getElementById('ObjectName'); Other times, it's done like this: var object = document.getElementById('#ObjectName'); What distinguishes ...

When passing context to createPage for use in a query, there may be issues if a string is inadvertently converted to a number, causing the query to fail

I am facing an issue with a page creation function that I have implemented. Here is the code snippet: createPage({ context: { productId: String(productId) }, Despite explicitly converting the ID to a string, the page template is still receiving it as a ...

The div element disappears upon calling the load() function

Currently, I am working to implement sorting criteria (such as by price or author) on my jsp page. I am utilizing ajax to refresh the content of a div when a new sorting option is selected. However, upon calling the reload function, the div just disappears ...

The div that scrolls gracefully within its boundaries

Currently, I am working on a task that involves a div containing images that need to be scrolled left and right. I have successfully implemented the scrolling functionality using jQuery. However, I now face the challenge of ensuring that the content stays ...

Leveraging the ReactJS Hook useState for detecting Key press events

As I am in the process of constructing a piano, I want it to showcase certain CSS styles when the user "presses" specific keyboard buttons (via keydown event) - even enabling the simultaneous clicking of multiple different buttons. Once the user releases t ...

Searching for values in an array using the $elemMatch operator in MongoDB 2.6 without the need for the $eq operator

Looking to retrieve all users with a specified objectId in an array. Here is the query I'm using: var query = { 'arrayOfIds': { $elemMatch: { $eq: id } }, }; This query functions well in mongodb 3.0. However, in mongodb 2.6, there isn& ...

Discover the magic of Material UI's Multiple Select feature for working with arrays

Utilizing the material-ui multiple select feature, I have set up a demo following the guidelines provided in the Multiple Select documentation. You can check out my example here: codesandbox In my demonstration, I am aiming to use 2 arrays for two separa ...

Is it possible to verify the absence of an error icon when valid data is provided in Angular testing?

Currently, I am utilizing the Selenium webdriver for Angular Automated testing. My scenario involves displaying a tooltip icon with an error message if the data provided is invalid. If the data is valid, the tooltip icon does not show up. Although, I have ...

How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>. Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and woul ...

Is there a way to modify or update the CSS classes and overall styling in .gsp files within the Grails framework?

What is the best way to dynamically update a DOM element's class and styling in response to specific conditions or events occurring in a .gsp file? ...

Is there a way to link the scrolling of two ag-grid data tables together for synchronized movement?

I have integrated ag-grid into my Angular project and I am looking to display two data tables (ag-grid) stacked on top of each other. Both data tables should scroll together, meaning when I scroll in table 1 or table 2, the content of both tables should m ...

Retrieving the values of multiple selected options from various select fields simultaneously

Picture having a dynamic number of select fields (the value of this variable is not fixed). I am looking to extract the values of the selected option from each select field using jQuery (or vanilla JavaScript). This is my approach: var cars = $(".sele ...

Maintain the flow of a floated or absolutely positioned element using CSS

Is there a way in CSS to ensure that floated or absolutely positioned elements remain within the flow? I find it frustrating that CSS lacks something like flow:on and flow:off to control this. The main issue I am facing is with having a div element of var ...

Notification of failed fetch in backbone

We are experiencing a problem with our backbone application. Our goal is to show a notification to the user when a fetch fails (due to timeout or general error). Instead of displaying an error message on a new page, we want to overlay a dialog on top of th ...

"Include the 'unsafe' prefix at the start of the URL in AngularJS

Whenever I attempt to access app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 within my app, the URL gets parsed as ==> unsafe:app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 Is ...

Is there a way to remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...

Mobile-style menu with full desktop height

I am currently working on developing my first custom WordPress theme from scratch. My goal is to design a mobile-style menu that can also be displayed on desktop screens. To achieve this, I have used jQuery to implement the sliding effect. You can view a ...

Is the state mutated when using the .map() function to update it?

I am new to working with React and I am still struggling to understand state mutation. After reading multiple posts on this topic, I am finding it difficult to grasp the concept of state mutation. So, I have decided to seek clarification on this matter. ...