Automatically hiding divs when clicked using HTML and CSS

Apologies if this question has been asked before, but I have two onclick divs and I'm trying to achieve a specific behavior. When I open the first one, I want it to automatically close when I open the second one, and vice versa.

Below is the HTML code snippet:


            function myFunction() {
                var x = document.getElementById("myDIV");
                if (x.style.display === "none") {
                    x.style.display = "block";
                } else {
                    x.style.display = "none";
                }
            }

            function myFunction2() {
                var x = document.getElementById("myDIV2");
                if (x.style.display === "none") {
                    x.style.display = "block";
                } else {
                    x.style.display = "none";                  
                }
            }
        

            #myDIV {
                position: relative;
                width: 100%;
                padding: 50px 0;
                text-align: center;
                background-color: lightblue;
                top: 150px;
            }

            .button1 {
                position: relative;
                top: 120px
            }
  
            #myDIV2 {
                position: relative;
                width: 100%;
                padding: 50px 0;
                text-align: center;
                background-color: lightblue;
            }

            .button2 {
                position: relative;
            }
        
 
            <button class="button1" onclick="myFunction()">Try it</button>

            <div id="myDIV">
                This is my DIV element.
            </div>

            <button class="button2" onclick="myFunction2()">Try it2</button>

            <div id="myDIV2">
                This is my second DIV element.
            </div>
        

DEMO: https://codepen.io/pen/NWrZBRX

Answer №1

To achieve the desired functionality, it is important to include both div elements in both functions. By doing so, you can then choose which one to hide and which one to show. Consolidating both actions into a single function simplifies the process as it essentially reverses the previous action taken. Additionally, ensuring that the button remains visible on top of the div container can be achieved by setting its z-index property to 1, preventing it from being hidden underneath the divs at times.

(you can implement these changes within your existing code as shown below)

  #myDIV {
    position: relative;
    width: 100%;
    padding: 50px 0;
    text-align: center;
    background-color: lightblue;
    top: 150px;
  }

  .button1 {
    position: relative;
    top: 120px
    z-index:1;
  }
  
  #myDIV2 {
    position: relative;
    width: 100%;
    padding: 50px 0;
    text-align: center;
    background-color: lightblue;
  }

  .button2 {
    position: relative;
  }
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>
            test
        </title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="legStyle.css">
    </head>
    <body>
        <button class="button1" onclick="myFunction()">Try it</button>
        <div id="myDIV">
            This is my DIV element.
        </div>
        <div id="myDIV2">
            This is my second DIV element.
        </div>

        <script>
            function myFunction() {
              const x = document.getElementById("myDIV");
              const y = document.getElementById("myDIV2");
              if (x.style.display === "none") {
                x.style.display = "block";
                y.style.display = "none"
              } else {
                x.style.display = "none";
                y.style.display = "block"
              }
            }
            </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

I possess an array with a specific structure that I wish to substitute the keys as demonstrated below

The data array is currently structured in this way. I have attempted various methods but have not been able to find a suitable solution. I need to send the JSON below via an AJAX request, however, I do not want the keys 0 and 1 in both child arrays. [sch ...

AngularJS is failing to properly register custom directives

Looking to enhance the SEO caching capabilities of my AngularJS website, I've embarked on implementing a couple of directives for custom page titles and descriptions. Incorporated within my app config (angular.module('website', [...'we ...

Something seems off with the color of the getImageData when using Fabric JS getContext('2d')

Website: Currently, I am working on adding an eye dropper feature to my website. It functions perfectly at a resolution of 1080p, but when tested on higher or lower resolutions, it malfunctions. Here is the basic code snippet: var ctx = canvas.getContex ...

Updating a specific row in a multiple row form can be achieved when the input field names match in a column

My task involves working with a report that generates a form in input mode. This form contains multiple rows of data, each row consisting of a button and an input field. The input field name remains consistent across all rows for easier processing by the C ...

Tips for composing a single aggregation within a query

In my query, I wanted to find the first record with a CREATE_DATE greater than or equal to a specific date and less than another date. After calculating the duration between these dates, I needed to write another query. However, I was unsure how to combine ...

What is the most effective way to loop through HTML elements using wildcards in Puppeteer to extract innerText?

Seeking insights for educational purposes, I am in search of the reviews on this specific page . Each page contains 10 reviews, and I have a set of HTML selectors (previously used code) to extract these comments: #review_593124597 > div:nth-child(1) &g ...

Image Animation Using a Rotational Control (HTML/JavaScript/...)

I am interested in achieving a specific effect with a series of images that transition from dark to light. My idea is to have a dial or slider underneath or over the frame so that when it is moved to the left, the black image is displayed, and when moved t ...

Is there a way to automatically populate my second dynamic dropdown list on page load?

I am currently working on a dynamic drop down menu that consists of two lists. When the page initially loads, the second drop down list is empty. However, I would like both lists to be displayed by default. You can see an example of the issue I'm faci ...

Issues with Forms Affecting my Footer

One of the best methods to understand this issue is to view it live. The footer on the homepage looks great at www.fishingreports.com. However, there seems to be a problem with the footer at www.fishingreports.com/users/register. Whenever I copy the cod ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

Does Firestore arrayunion offer any kind of callback function?

Hey there! I'm currently working on a voting system and I want to prevent the same user from voting multiple times on the same post. let db = firebase.firestore(); var postRef = db.collection("posts").doc(this.pid); postRef.update({ ...

Choose a navigation item from the list containing a nested span element

I've implemented selectnav from GitHub and it's functioning perfectly. However, my menu consists of list items with a description span inside each one, resulting in menu items structured as shown below: <li><a href="somelink.html">Ch ...

I am struggling to style a form effectively with CSS grid

I am working on setting up a 2-column HTML form using CSS grid. In the first column, I have labels placed on individual rows. In the second column, I have form elements also placed on individual rows. This is my initial attempt at this task and I am sti ...

Node JS server fails to load CSS even with the use of express.static

It's quite absurd, but I've been grappling with a rather nonsensical code conundrum for days now. I just can't seem to get the CSS and image to load on my Node.js server. I've tried various solutions (like express.static, etc.), but n ...

Techniques for parsing a String in Objective-C

I am looking to parse a string to replace certain elements within it. If the string contains an <ol> tag, I want to specifically focus on replacing the <li> elements with numbers. I understand that I can utilize the rangeOfString method to c ...

Invoke two functions simultaneously on a single Onchange event

Can someone help me understand how to trigger two functions by changing the value of a specific dropdown list using the "OnChange" event in Ajax? Note: The system typically only displays the output of the showhistory() function. Here is my existing code: ...

The vertical writing mode is causing boxes to stack in an unexpected direction

I am encountering an issue with three div elements that have a writing-mode of vertical-rl. Despite setting the writing mode to vertical, the block stacking context is not being displayed from left to right as expected, but rather stacking inline. CSS .v ...

Apply CSS code to create a fading effect for a container

Below is the code for my accordion list, created using only CSS and HTML. Whenever a heading is clicked, the text slides in with a different background color. How can I make it so that the container with the text and different background color fades in and ...

When using Vue computed, an error is thrown stating "Issue in rendering: 'InternalError: too much recursion'" if the same key is referenced in computed

As a newcomer to Vue, I wanted to track how many times a function in the computed section gets called. To achieve this, I created the following component: const ComputedCounter = { name: "ComputedCounter", template: ` <span>{{ value } ...

When using Node.js with Express and ssh2, my data structures remain intact without any resets when loading web pages

To display jobs sent by users to a cluster, the code below is used (simplified): var split = require('split'); var Client = require('ssh2').Client; var conn = new Client(); var globalRes; var table = [["Head_1","Head_2"]]; module.exp ...