Switch Button JavaScript Library

My project involves creating a mobile website with a simple interaction where clicking on a div opens another div underneath it. The HTML structure consists of two stacked divs, with the CSS for the bottom div initially set to 'none'. Using JavaScript, an event listener is triggered by a click on the top div, changing the display property of the bottom div to 'block' and revealing it. How can I modify the code so that clicking on the top div again will hide the bottom div by setting its display back to 'none'?

Here is the current basic code snippet:

document.getElementById('divOne').addEventListener('click',function(){
    document.getElementById('divTwo').style.display = 'block';
});
#divOne {
    border: 1px solid black;
}

#divTwo {
    border: 1px solid black;
    display: none;
}
<div id="divOne">Click me</div>
<div id="divTwo">Hello World!</div>

    

Answer №1

To determine if the element has display: block set, you can simply check the style attribute.

document.getElementById('elementOne').addEventListener('click',function() {
    var elementTwo = document.getElementById('elementTwo');
    if(elementTwo.style.display === 'block') {
        elementTwo.style.display = 'none';
    } else {
        elementTwo.style.display = 'block';
    }
});
#elementOne {
  border: 1px solid black;
}

#elementTwo {
  border: 1px solid black;
  display: none;
}
<div id="elementOne">Click me</div>
<div id="elementTwo">Hello World!</div>

Answer №2

To ensure the visibility of an element, you can first check if it is set to 'none' and then toggle it to 'block' or vice versa. I prefer storing the DOM Object of the specific element in a variable for cleaner code organization.

document.getElementById('divOne').addEventListener('click', function() {
  var secondDiv = document.getElementById("divTwo");
  secondDiv.style.display = secondDiv.style.display === 'none' ? 'block' : 'none';
});

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

Tips for effectively crafting a component capable of managing both a value and an observable for that specific value

I'm actually curious about two things. When is it appropriate to pass an observable of an object into a component versus resolving it with the | async method? If I want to create a versatile reusable component that can handle both scenarios - accept ...

Steps to avoid TypeError: e.target.getAttribute is not a function

My goal is to make the inner code (result) function only when a Validity attribute is present. However, my target lacks said attribute, so I'm looking for a way to use an if statement to prevent the inner code from executing. How can I avoid the Type ...

When the width of the screen is less than 992 pixels, my div will be hidden

I have been working with the bootstrap4 layout, and I noticed that when the screen width is less than 992px, the yellow-div is overlapping the brown-div. Can someone explain why this is happening and suggest a solution? Below is the code snippet: .head ...

Is there a way to align text in the middle of a full-width jumbotron using bootstrap 4 while also restricting the maximum width of only the div or p container?

Trying to master the art of using Bootstrap 4 has been quite a journey. At first, everything seemed to work smoothly as I attempted to horizontally center some text within a full-sized jumbotron. However, things took an unexpected turn when I decided to im ...

Updating the index page with AJAX in Rails 4: Step-by-step guide

It's surprising that I haven't found answers to my specific questions despite searching extensively. I have an Expenses page where I want to display all expenses for a given month in a table. Currently, I achieve this by adding month and year par ...

Utilizing the principles of object orientation in Javascript to enhance event management

After attempting to modularize my JavaScript and make it object oriented, I found myself struggling when dealing with components that have multiple instances. This is an example of how my code currently looks: The HTML file structure is as follows: & ...

Retrieve the initial value of the input element following a modification

Is there a way to retrieve the original default value of an input field after changing it using .val()? In my HTML, I have various text-inputs with classes .large and .medium, each with its own default text value. What I'm trying to achieve is when a ...

Insert a fresh row into the gridview using JavaScript

I am working with a grid view where I dynamically add new rows using JavaScript. Each row in the grid view contains an image (addButton), which triggers a specific JavaScript function when clicked. function AddNewRecord(e) { debugger; var hfFirst ...

Sharing information between controllers while being initiated using $rootScope.$emit

I've created a common module that includes a controller, component, and template to initialize the app and set up the base layout. Within this module, there is also a stateful component that makes an HTTP GET request during initialization to fetch a b ...

The appearance of a <div> element results in a border being applied to a different element

When hovering between the two borders, an undesirable (albeit very small) border appears around them. Can anyone assist me with this issue and explain why it is happening? I have attempted to set a transparent border on each element but without success. R ...

What causes the Next 13 App to reload when the route is changed?

I am currently working on the Next 13 Application and facing an issue where clicking on navigation links from the sidebar changes the route, but unfortunately, the application is getting reloaded. It should ideally replace the component directly without re ...

Exploring FabricJs: Reassessing the coordinates of an object post-rotation

const canvas = new fabric.Canvas("c", { selection: false }); const refRect = new fabric.Rect({ left: 250, top: 150, width: 200, height: 100, fill: 'transparent', stroke: 'blue', originX: 'center', originY: & ...

A peaceful WCF service initiates a client callback whenever a server update occurs

In the process of developing a WCF RESTFUL service on top of a c++ console application, I am confronted with an issue. The client accesses this c++ application through my restful wcf service using a browser. Every time there is an update received by my w ...

Generate a unique identifier for the button by extracting the value from a string

Hey there, I'm new to this platform and have a question. Here's what I'm trying to figure out: In my value/strings.xml file, I have the following data: <string name="bm">Mengawal</string> <string name="bi">Managing</st ...

Creating an import map using jspm2 can be done by following these steps

Currently, my goal is to utilize JSPM module loader to import javascript packages from npm instead of CDN and employ an offline package loader. Now, the next step involves incorporating an importmap script in order to successfully import modules like rea ...

The Angular-Express combination is not being satisfied by the get request

`, I am a newcomer to the MEAN stack environment and I am struggling with fetching data from my Express server (which is set up with MongoDB) when a button is clicked. Even though the function associated with the button click is executed, the request does ...

SVG Mask not functioning properly with SVGs created in Illustrator (in all web browsers)

Alright, let's get to it - I've got a couple of SVGs here. The first one is a blue circle and the second one is a map of the United States. (Both of these were created in Illustrator) Here's what I want to do: I want the map to serve as a ...

Is there a way to use jQuery to permanently add elements and have them incrementally numbered, such as Cam 1, Cam 2, Cam 3, and so on, while using an iframe?

https://i.sstatic.net/XaYGc.pngRecently, I implemented a video streaming feature on my website. The default camera displayed is Cam 1 as shown in the code snippet below: <div class="card mb-3"> <div class="card-header"> <i class ...

issue with react prop causing my function to function in one scenario but fail in another

I'm a bit confused with these two functions. Although they seem identical to me, only the first one is able to generate images from this.state.images. Any guidance on this seemingly small mistake would be much appreciated. The following code snippet ...

Modify the width of the inner or child elements

My parent container can contain either 1, 2, or 3 child elements. When there is only one child element, it should take up 100% of the width. If there are two child elements, they should each have 50% of the available width. And if there are three child e ...