Using jQuery, how can I dynamically change the stacking order of an element when clicked?

I'm struggling to change the z-Index on button click. I have a static image and a dynamic div, and I want to send the #imgDiv1 behind the static image. Unfortunately, despite trying everything, I haven't been able to achieve this.

You can check out the live demo here: jholo.com. My goal is to implement this concept in my web application.

Here is the structure of my HTML:

<div id="safeZone">
    <img src="default.png" />

    <div id="imgDiv1">
         <img src="myPic.jpg" />
    </div>

</div>

<input id="back" type="button" value="Send To Back"/>
<input id="front" type="button" value="Bring To Front"/>

And here is the jQuery code:

 $(document).ready(function(){ 

   $("#back").click(function(){
      $("#imgDiv1").css("z-index","-10");
   });

   $("#front").click(function(){
      $("#imgDiv1").css("z-index","10");
   });

});

Answer №1

The CSS property z-index will only have an effect on elements that are not using position: static. Therefore, you must set the position property before the z-index can take effect.

Here is some example HTML:

<button id="up">Up</button><button id="down">Down</button>
<div id="container">
    <img id="img1" src="http://dummyimage.com/300x200/ff0000/fff.jpg">
    <img src="http://dummyimage.com/300x200/00ff00/fff.jpg">
</div>

And the accompanying CSS:

#container img {position: absolute;}
#container {height: 200px; width: 300px;}

JavaScript code snippet:

$("#up").click(function(){
     $("#img1").css("z-index", -10);
  });

$("#down").click(function(){
    $("#img1").css("z-index",10);
});

You can see a working demo at this link: http://jsfiddle.net/jfriend00/5Efm3/


Edit - Responding to your additional edit:

In order to achieve the desired effect, the snowflake image should have transparency within the snowflake shape to allow the background image to show through. This means it should not be in JPG format, but rather GIF or PNG would be suitable options.

Answer №2

Opting for opacity over z-index seemed to do the trick for me... did you find it helpful?

$("#down").click(function(){
 $("#img1").css("opacity", 0.0);
$("#img2").css("opacity", 1.0);
  });

$("#up").click(function(){
$("#img2").css("opacity",0.0);
$("#img1").css("opacity", 1.0);
});

If you need more clarity, I've included a link to the js fiddle: http://jsfiddle.net/6rwBR/. Hopefully this sheds some light on things.

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

If the div element is present on the page, incorporate additional class and attributes to enhance its functionality

Similar Question: How to add new class and attributes to div if it exists on the page I am in search of JavaScript code that can be implemented on my master page. This code should check for the existence of a specific div, and if found, it should add ...

Ways to enhance numerical count and showcase it on a dynamically inserted div using jQuery

There is a link on top of a static div that is already loading by default (Div number 1). As shown in the image, each time I click on the hyperlink, a new div is added beneath every existing one. I want to be able to increase the count of the div numbers ...

Vue.js: Issue with applying class binding while iterating over an object

I've been working with an object data that looks like this: object = { "2020092020-08-01":{ "value":"123", "id_number":"202009" }, "2020092020-09-01":{ "value& ...

After props have been passed, the ReactJS ComponentWillMount() function is triggered

Can anyone explain why the child component is only rendered once, even though I pass props to it every time I click a button? Whenever I click a button that passes props to the child, the ComponentWillMount() method of the child component doesn't tri ...

Dynamic Rendering of Object Arrays in Table Columns using JavaScript

In the process of developing an appointment slot selection grid, I have successfully grouped all appointments by dates. However, I am facing challenges in displaying this array of Objects as a clickable grid with columns. The current output can be viewed h ...

Display the changing value at the beginning of the drop-down menu

I'm currently working on an AngularJS forEach loop where I need to display a dropdown list with dynamic values. The goal is to have the value stored in $scope.showCurrentProgram as the first selected element in the dropdown list when the page loads, a ...

React and Material-UI issue: Unable to remove component as reference from (...)

My React components are built using Material-UI: Everything is running smoothly MainView.js import React, { Component } from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { List, ListItem } from ...

The line breaks in elements occur when the combined widths add up to 100%

Is there a way to display an input and a button inline, with the input taking up 70% of the row and the button taking up 30%? I tried setting the CSS for the input to 70% and the button to 30%, but they keep breaking onto separate lines. How can I solve ...

Contenteditable feature dynamically styling text upon input

Is it possible to prevent CSS properties like text-transform from affecting text entered via contenteditable? On my webpage, "CERTIFICATE PROGRAM" is shown in uppercase due to text-transform settings. However, the original input was: Certificate Program. ...

Achieving functionality with a fixed header

I am struggling with the scroll functionality and smooth transition in my code for a sticky header. The scroll doesn't work smoothly, especially when the fixed header is activated. The #top-nav-wrapper barely scrolls as expected: <script> $(doc ...

Obtain a compilation of users who have expressed their reaction to a message with a specific emoji on Discord

Check out this Discord.js code snippet for a Discord bot: client.channels.fetch('channelID here').then(function (channel) { channel.messages.fetch('messageID here').then(function (message) { console.log(message.reactions.cache.get(&a ...

npm not working to install packages from the package.json file in the project

When using my macbook air, I encounter an issue where I can only install npm packages globally with sudo. If I try to install a local package without the -g flag in a specific directory, it results in errors. npm ERR! Error: EACCES, open '/Users/mma ...

Implement a click event using jQuery specifically for Internet Explorer version 7

How can I add an onclick attribute using jQuery that is compatible with IE7? So far, the following code works in browsers other than IE8 and Mozilla: idLink = Removelst(); var newClick = new Function(idLink); $(test1).attr('onclick', null).clic ...

Pop-up box with hyperlink

I successfully integrated multiple modals into my webpage, using a template from w3school that I customized. Now, I am curious to see if it is possible for each modal to have its unique link. For example, when I open Modal 4, the URL would change to myweb ...

Exploring creative methods for incorporating images in checkboxes with CSS or potentially JavaScript

Although it may seem like a basic question, I have never encountered this particular task before. My designer is requesting something similar to this design for checkboxes (positioned on the left side with grey for checked boxes and white for unchecked). ...

"What is the best way to use jQuery to create a toggle effect where one button controls the state

I'm looking to improve the efficiency of my code, but I'm not sure where to start in terms of making it more concise and organized. Any suggestions on how to streamline this code and keep it neat would be greatly appreciated. $(document).ready(fu ...

Creating interactive dropdown menus with PHP and Catalyst using Jquery

Currently, I am working on incorporating cascading dropdown menus into a catalyst web app. The main goal is to allow users to select a database table from the first dropdown menu and have the columns of that table populate the second dropdown menu. To achi ...

Executing sequential jQuery ajax requests with a REST API

I need a little help and hope you can assist me with my somewhat challenging problem. I have a REST API collection where URL1 provides a list of names, and URL2 contains properties related to the names from URL1 (e.g., URL2?name=URL1.name). Example: URL1 ...

Date parsing error thrown by jQuery datepicker plugin

What could be causing the InvalidDate exception when attempting to parse the date using $.datepicker.parseDate("mm/yy","02/2008");? ...

Ways to eliminate extra space from the edges of a container

Trying to wrap my page in a Material UI container component, but there's this persistent whitespace on the outside that no matter how much I tweak the margin and padding, it just won't disappear. Any CSS wizard out there with a workaround to make ...