What is the best way to stack several elements on top of each other?

<div class="parent">
  <div class="child" id="child-A">
  <div class="child" id="child-B">
  <div class="child" id="child-C">
</div>

The main concept here is that initially, child-A will be on top, hiding child-B and child-C since they will be positioned below child-A.

There will be a feature that allows toggling to adjust the width of each child element, determining which ones are visible and which ones are hidden.

Answer №1

var checkboxes = document.querySelectorAll( 'input[type=checkbox]' );

function toggleCheckbox(event) {
    var attribute = event.target.getAttribute("data-target");
    var element = document.getElementById(attribute);
    if (element.style.display === "none") {
        element.style.display = "block";
    } else {
        element.style.display = "none";
    }
}

for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('change', toggleCheckbox, false);
}
.child{
width:200px;
height:200px;
position:absolute;
}

#child-A{
background:red;
z-index:100;
}

#child-B{
background:blue;
z-index:99;
}

#child-C{
background:yellow;
z-index:98;
}

#controls{
margin-left: 210px;
}
<div class="parent">
  <div class="child" id="child-A"></div>
  <div class="child" id="child-B"></div>
  <div class="child" id="child-C"></div>
</div>

<div id="controls">
<label><input type="checkbox" data-target="child-A" checked/> Child A </label> <br>
<label><input type="checkbox" data-target="child-B" checked/> Child B </label> <br>
<label><input type="checkbox" data-target="child-C" checked/> Child C </label> <br>
</div>

Answer №2

To reach your objective, utilize CSS properties like position and z-index. To toggle the active state, manipulate the class of the element with JavaScript. Below is a straightforward example where clicking on the black area will toggle the active state.

let i = 0;
const children = document.querySelectorAll('.child');

function toggleDiv() {
  children[i].classList.remove('active');
  i = (i + 1) % 3; // considering we have 3 children
  children[i].classList.add('active');
}
.child {
  position: absolute;
  height: 100px;
  width: 100px;
  font-size: 20px;
  background: black;
  color: white;
}

.child.active {
  z-index: 1;
}
<div class="parent" onClick="toggleDiv()">
  <div class="child active" id="child-A">child-A</div>
  <div class="child" id="child-B">child-B</div>
  <div class="child" id="child-C">child-C</div>
</div>

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

What components and substances are needed for a particle system in Three.js?

After spending a few weeks working with particle systems in Three.js, I initially used an Object3D, incorporating my own Vector3s and various materials like MeshBasicMaterials, Phong, and Lambert. However, after discovering the built-in ParticleSystem obje ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

Creating intricate structures using TypeScript recursively

When working with Angular and TypeScript, we have the power of generics and Compile-goodness to ensure type-safety. However, when using services like HTTP-Service, we only receive parsed JSON instead of specific objects. Below are some generic methods that ...

How to easily toggle multiple elements using jQuery

I'm having trouble getting this block of code to function properly: $("a.expand_all").on("click",function(){ $(this).text('Hide'); $('.answer').each(function () { $(this).slideDown(150, function () { $( ...

JS/Docker - The attribute 'user' is not recognized in the context of 'Session & Partial<SessionData>'

I'm attempting to integrate express-session into my Node.js application running within Docker. I've come across several discussions on the topic: Express Session: Property 'signin' does not exist on type 'Session & Partial<Se ...

Are there alternative methods for handling routes in React, other than using the react-router-dom@latest library?

Currently, I am focused on a frontend project. One of the tasks at hand is to configure the network of routes. During my research, I came across react-router-dom@latest as a potential solution. However, I am curious to explore alternative options availa ...

Executing a function within another function (triggering the logout action by clicking the logout link) in ReactJS

Is there a way to access a method outside the render function and call it inside another function in order to log out the user with a simple click? I encountered the following error: Cannot read property 'AuthLogout' of undefined Let me shar ...

Adjustable background image with no need for a scroll bar

I am looking to create a static webpage that remains fullscreen without any scrolling. My goal is to have a centered form with the background image adjusting to the window size. As a beginner, I apologize if this request seems too simple. .container { ...

Ensure that you decode the URL before making any changes to the location in a

Hi everyone, I'm facing an issue and need your help. Let's say we have a URL like site.com/post?comments=1,2,3,4. When I paste it into the browser address bar, my app opens and decodes the URL to site.com/post?comments=1%2C2%2C3%2C4. How can I re ...

Challenges of relative positioning with dynamic height based on content

Hello! I'm trying to achieve this https://i.stack.imgur.com/Q6lXP.png In this case, there are 3 divs. The top one will have a width of 100% and a height of auto, with relative positioning. The second div is similar, but I plan to add some dummy text ...

Allowing access from different domains when using Angular.js $http

Whenever I encounter a CORS issue while developing a webapp, my go-to solution is to brew some coffee. However, after struggling with it for some time, I am unable to resolve the problem this time and need assistance. Below is the client-side code snippet ...

looping through the iteration

Here is a link to my original plunker demonstration: http://plnkr.co/edit/9UBZ9E4uxAo1TXXghm1T?p=preview. In the case of div 4 (ng-if="show==4"), I am looking for a way to hide the particular div when the list is empty. Currently, each div is displayed fo ...

Using images in R Shiny with htmlTemplate: A step-by-step guide

In my current project, I have a file named template.html that I am loading using the code snippet below: https://i.sstatic.net/TipvS.png One issue I'm facing is including an image in this template.html file. Despite having the correct relative path ...

Creating an image using tiles in HTML

I have divided an image into 48 tiles (8x6) using a method similar to "Cutting an Image into 9 pieces C#". Now, I want to reconstruct the original image in HTML. What is the most effective approach to achieve this? Initially, I attempted to use a table wi ...

What is the rationale behind not passing $scope to a service in AngularJS, and is it considered bad practice?

Is it advisable not to pass $scope to a service for certain reasons? I understand that services are intended to be reusable singletons, and passing a (potentially) large object to the service could lead to maintenance issues. However, assuming there is so ...

Removing the element generated by Angular from the DOM

I've hit a roadblock with this issue. Here is the delete function in my mainController. $scope.delete = function($posts) { $http.delete('/api/posts/' + $posts._id) .success(function(data) { // remove element from DOM ...

Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) ...

Color the area entirely in black

I am currently working on a project for one of my courses, where I have created a website for a specific service. However, I am facing some challenges and things are not going as smoothly as I had hoped. Here is a screenshot of the page: https://i.stack.im ...

Moving information from one controller to another, or the process of converting a controller into a service

Is there a way for me to transfer information from one controller to another? Or can I create a service from a controller? Specifically, I am looking to retrieve coordinates and store them in an object along with other variables. When I try to inject depen ...

Order the variables in the dropdown menu based on the PHP variables

I currently have a select list that allows me to choose between two options: Popularity and Recently Ordered. My goal is to filter the objects on the page based on these attributes, connecting each option to its respective function in my dataloader.php fi ...