Adjust the ZIndex on a div through interactive clicking

For my new project, I'm exploring a concept inspired by Windows 7. The idea is that when you double click on an icon, a window will open. If you keep double clicking on the same icon, multiple windows should appear. The challenge I'm facing is implementing the z-index functionality to ensure that the clicked window comes to the front among others. Currently, the code only allows one window to open upon clicking an icon, and subsequent clicks do not trigger any action.

let pc = document.getElementById('pc')
// Remaining JavaScript code...
// CSS styles...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    // Head content...
</head>
<body>
    // HTML structure...
    </body>

</html>

Answer №1

If you want to enhance the functionality, try incorporating a class named "active" with a z-index of 2. Then, set up an eventListener on the window that includes the addition of the "active" class.

To visualize this concept, I created a Fiddle:

In my CSS, I introduced a class known as "active"

/* include this class */
.active {
  z-index: 2;
}

Subsequently, in JavaScript, I included the following code:

// This snippet makes the window active
newWindow.addEventListener("click", () => {
if (document.querySelector(".active")) {
document.querySelector(".active").classList.remove("active");
}
newWindow.classList.add("active");
})
// End of the snippet

Whenever a window is clicked, any pre-existing "active" class gets removed. Following that, the selected window receives the "active" class designation.

Answer №2

Implementing dynamic z-index values

To achieve this dynamically, one approach is to maintain a global variable named zIndexCounter initialized to 0 at the start (or any other starting value of your choice). Whenever a new window is created, assign it a z-index value equal to the current counter value, then increment the counter.

This method guarantees that each subsequent window will always have a higher z-index compared to the previous one.

Answer №3

I came up with an alternative approach without using z-index. Instead, I created an array to manage the order of opened windows. When a window is clicked, it moves to the end of the array, ensuring it appears on top of other windows. The old windows are removed and replaced with the rearranged new windows.

You could also incorporate zIndex, but based on my process, it's unnecessary.

windows.forEach((elem) => body.appendChild(elem)); // add rearranged windows to page

Additionally, you can include the following code snippet inside the forEach loop:

windows.forEach((elem, i) => {
  elem.style.zIndex = i;
  body.appendChild(elem);
}); // add rearranged windows to page

/* Also make sure to add this in the double-click function */
window.style.zIndex = len();

I made quite a few modifications throughout the code:

  1. Applied the class .new_window to simplify the selection of windows opened via double click.

  2. Eliminated redundant functions, elements, and classes within the JavaScript, HTML, and CSS sections.

// JavaScript Code
const items = [{
    icon: document.getElementById("pc"),
    class: "pcwindow",
    html: `<input class="b" type="button"><img id="setting" src="content/img/Settings-Icon-Graphics-15383788-1-580x374.jpg" style="width: 130px;height: 100px; margin-left: 15px;"><img id="folder2" src="content/img/folder2.png" style="width: 100px;height: 100px; margin-left: 15px;">`
  },
  {
    icon: document.getElementById("folder"),
    class: "folderwindow",
    html: `<input class="b" type="button"><img id="pic" class="folderwindow" src="content/img/pic.png" style="width: 100px;height: 100px; margin-left: 15px;"><img id="f2" src="content/img/folder2.png" style="width: 100px;height: 100px; margin-left: 15px;">`
  },
  {
    icon: document.getElementById("bin"),
    class: "binwindow",
    html: `<input class="b" type="button"><img id="f3" src="content/img/folder2.png" style="width: 100px;height: 100px; margin-left: 15px;"><img id="f4" src="content/img/folder2.png" style="width: 100px;height: 100px; margin-left: 15px;">`
  },
];
const body = document.querySelector("body");

// Get the current number of windows
const len = () => document.querySelectorAll(".new_window").length;

// Move the clicked window to the top
const toTop = (e) => {
  let windows = [...document.querySelectorAll(".new_window")]; 
  if (windows.length <= 1) return; 
  windows.forEach((elem) => elem.remove()); 
  windows.push(windows.splice(windows.indexOf(e.target), 1)[0]); 
  windows.forEach((elem) => body.appendChild(elem)); 
};
const closeWindow = (e) => {
  e.target.parentElement.remove();
};
items.forEach((d) => {
  d.icon.addEventListener("dblclick", () => {
    let window = document.createElement("div");
    window.className = `d new_window ${d.class}`;
    window.innerHTML = d.html;
    window.style.display = "block";
    window.style.top = `${25 + 25 * len()}px`;
    window.style.left = "100px";
    body.appendChild(window);
    window.addEventListener("click", toTop);
    window.querySelector(".b").addEventListener("click", closeWindow);
  });
});
// CSS Code
body {
  background-image: url(img/150-1509609_hd-abstract-wallpaper-neon-smoke-71-images-colorful.jpg);
  background-repeat: no-repeat;
  background-size: cover;
  margin: 0;
}

.folder {
  width: 80px;
  height: 80px;
}
...
<!-- HTML Markup -->
<div class="pc">
  <img id="pc" class="d pc" src="content/img/Gabriel-Leblanc-Historic-Mac-Mac.512.png" alt="">
</div>
<div id="folder" class="folder">
  <img class="folder" src="content/img/folder.png" alt="">
</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

The property being set in Angular is undefined, causing an error

I am struggling to understand why the code below is not functioning as intended: Main.html <div class="MainCtrl"> <h1>{{message.test}}</h1> </div> Main.js angular.module('myApp') .controller('MainCtrl', f ...

How can I fix the position of the close button when using the paper component of a modal in material ui to ensure responsiveness on the screen

I recently created a cards page where multiple cards are displayed. Each card opens a modal component when clicked, but unfortunately, the close button is not functioning properly. Here's an image showing the issue with the button's position whe ...

What is the best way to change the maxWidthLg of Material UI's .MuiContainer?

I need to remove the max-width that is set in the theme. When I look at it in Chrome and uncheck the option, it functions as desired: @media (min-width: 1280px) .MuiContainer-maxWidthLg { max-width: 1280px; } How can I achieve this? I have attempted ...

Which approach is more impactful: consistently sending an ajax request or breaking down the result within a function?

My JSON data consists of news entries with titles, text, and dates. Here is an example: { "news": [ {"title": "some title #1","text": "text","date": "27.12.15 23:45"}, {"title": "some title #2","text": "text","date": "26.12.15 22:35"}, ... ...

Customizing the appearance of two separate tables

I have a pair of tables that I want to style differently. Table 1 needs the images centered with no border, while table 2 should have text left-aligned with a border. Here is the CSS: table, th, td { border: 1px solid #999; border-collapse: colla ...

Ways to prevent users from pushing multiple child data or adding more than one child to a specific child in the Firebase database

How can we limit users from pushing more than one piece of data to the Firebase database in terms of security rules? I have attempted this approach without success. { "rules": { ".read": false, ".write": false, "voters": { // En ...

jQuery Files in Conflict

The issue I am facing involves the code below. The first function requires linked js and css, while the second one needs a jQuery and javascript file inherited from base.html. However, there seems to be a conflict in loading these files (possibly because o ...

Tips for incorporating line breaks into a contenteditable div using the key combination of ctrl + enter

$("#contenteditable").keydown(function(e) { var last = false; if (e.keyCode == 13) { if (e.ctrlKey) { let brNode = document.createElement('br'); let range = window.getSelection().getRangeAt(0); ...

Decrease the size of the "subscribe" button

Our "subscribe" button is currently displayed like this: https://i.sstatic.net/toiOb.png However, we are looking to reduce the extra width and have it appear more like this: https://i.sstatic.net/NaaYJ.png We are using the same code for both versions: ...

Unable to render Material Icons on Vue/Quasar web app hosted on Azure

I am facing an issue with my webapp built using Vue and Quasar. I added the necessary icon imports to my quasar-user-options.js file. import '@quasar/extras/material-icons/material-icons.css' import "@quasar/extras/material-icons-outlined/ma ...

I am attempting to implement a feature that changes the color of buttons when they are clicked within an ng-repeat loop

A problem is occurring with the ng-class directive in this HTML code, which is generating seats using the ng-repeat directive. The colors are not being added properly when a seat is selected. If you'd like to view my code, it can be found in this JSf ...

Implementing a Slide animation in React

I am currently working on a carousel feature that includes two buttons, Next and Previous. When the user clicks on Next, I want the carousel to slide from left to right, and when they click on Previous, it should slide from right to left. One important not ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

Tips for accessing values from a bs4 result set in Beautiful Soup?

Is there a way to extract all the title values from this bs4 result set? [<span class="zaman" title="16.3.2022 15:22:44">1 hf.</span>, <span class="hide zaman pull-right ml-5 mt--1">( Message Deleted )</sp ...

Sending STATIC_URL to Javascript file in Django

What is the most effective method for transferring {{ STATIC_URL }} to JavaScript files? I am currently using django with python. Thank you in advance. Best regards. ...

Listening to React events on multiple elements in an array

When my React render function is running, it ends up rendering a group of elements: data.map((element) => { return <Object onChange={this.onObjectChange} />; }); I'm wondering, what is the best approach to determine which specific object ...

In Visual Studio, make sure to include a reference to AngularJS.min.js within another JavaScript file

In my AngularJS app, I am utilizing Visual Studio with separate folders. The AngularJS-min.js file is located in a different folder. My query is how can I correctly reference the AngularJS-min.js file in my app's JavaScript file to enable auto-suggest ...

Managing Actions in React-Redux: Understanding the Dispatch Function

While I am delving into the world of React, I stumbled upon an example that looks like this: //index.js const store = createStore(reducer) render( <Provider store={store}> <AddTodo /> </Provider>, document.getElementById(' ...

What is the method for determining the width of a Mat-Table once it has been displayed?

When utilizing Angular Material Mat-Table in conjunction with Angular 8, I am passing the dataSource dynamically. The number of rows and columns varies each time. Is there a method to calculate the width of the table once it is rendered on the screen? &l ...

Both if and else statements are carrying out code in JavaScript/jQuery

The second if statement is functioning correctly, but the first one always triggers the else statement and never stands alone. This jQuery function is enclosed within another function that is invoked under the "$(document).ready" command. I resorted to u ...