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

Uncovering the enum object value by passing a key in typescript/javascript

How can I retrieve the value of an enum object by passing the key in typescript? The switch case method works, but what if the enum object is too long? Is there a better way to achieve this? export enum AllGroup = { 'GROUP_AUS': 'A' &a ...

Error in Rails app when incorporating Stripe API with Javascript involved

Incorporating Stripe into my rails app using the Koudoku gem has been challenging. When attempting to load the page for capturing user credit card information, I encounter an error in my JS console: Uncaught ReferenceError: $ is not defined (anonymous fun ...

What steps can I take to expand this on a grander level?

I have a code snippet for a personality quiz, but I'm facing an issue with increasing its size. Here's the HTML code: <h3>1. What is your favorite color?</h3> <input type="radio" name="q1" value="A" /> A. Red. <input type="r ...

Discovering elements with Selenium

While using selenium, I stumbled upon this web element: <td style="padding-right: 10px; " **onclick="javascript:show_me('CarDetails.php?CarID=2358912&SubCatID=1**', '2358912', 560, 'ActiveLinkVisited');stat( '../& ...

What is the best approach to streamline and optimize this JavaScript logic code for greater efficiency?

Working on a project, I find myself dealing with 21 buttons that can be in either an active or inactive state. The state of certain buttons is influenced by the press of other buttons as well as their own activation. To handle this in my HTML, I utilize ng ...

Navigating efficiently with AngularJS directives

Hello, I am currently searching for a solution to dynamically modify the navigation links within the navigation bar based on whether a user is logged in or not. Of course, a logged-in user should have access to more pages. I have developed a UserService t ...

Adjust the border color of the <input> element when it is clicked on

I'm currently working on a login screen for my next.js application and I've encountered an issue where the border color changes to a mixture of white and blue when I select an input field. https://i.stack.imgur.com/R2yKa.png I attempted to reso ...

Matching nodes to selectors is a breeze with Angular JS and jqLite

Currently, I am in the process of integrating a few jQuery functions into jqLite to avoid loading the entire jQuery library when working with my angular applications. Following the approach outlined by Ben Nadel in his insightful article. However, I have ...

Tips for sending an array of input field values through an Ajax request

In my current web form, there is a dynamic option that adds rows with the same attributes. These rows need to be submitted through an Ajax call to my PHP for insertion into the database. Access: <tr> <td><input type"text" name="access[nam ...

Nativescript apps are unable to utilize Node modules

I am currently facing an issue with integrating multiple plugins into my Nativescript application. The computed path to locate these installed plugins appears to be incorrect, and I am unable to locate any guidance on how to rectify this issue. Is there a ...

Resolve the potential jQuery conflict between Lightbox2 and FancyBox

Hey there, I recently took over a project for a website . However, no matter what type of lightbox I try to implement, I can't seem to get them to display properly. I suspect it's due to a jQuery conflict issue, but my skills in jQuery are quite ...

Getting the 3D Object Script in Three.js: A Step-by-Step Guide

I've been experimenting with three.js, specifically the Editor feature that allows you to attach scripts to 3D objects. In Unity 3D, accessing a script is as simple as using something like : targetGameObject.GetComponent (scriptName).targetVariable; ...

Tips for ensuring the alignment of a table header and body once data has been loaded into it

I am currently developing an Angular 7 application where I am trying to populate a table with data retrieved from a web service. However, the issue I am facing is that the headers of the table do not align properly with the body content after loading data ...

What is the best way to have dual backgrounds displayed on a single webpage?

Looking to recreate the background design featured on this website: www.zucoffee.com. Does anyone have any tips? In addition, I'm curious about how to achieve that curved separation effect. I understand it involves two divs, but how did they manage t ...

Safeguard sub-pages with Passport Local if the user has not logged in

I attempted to follow a tutorial on local authentication with Passport and Express, but I am encountering difficulties in protecting my pages for users who are not logged in. My goal is to redirect them to the login page. I experimented with creating midd ...

I'm having trouble getting the float left to work properly in my HTML/CSS code

Currently, I am diving into the world of HTML / CSS on my own. After following some tutorials, I have taken the leap to work on my very first project. My goal is to layout three images and three text elements on a single page using CSS. The desired struct ...

Is the primary color modification in Bootstrap failing to take effect?

Currently, I am working on a react app and I have successfully integrated Bootstrap React. One of the tasks I wanted to accomplish was changing the primary color from the default blue to a different shade. To do this, I navigated to bootstrap/scss/variabl ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

AngularJS utilizes JSON objects to store and manipulate data within

My task requires accessing information from an array that is nested inside another array in Json format. Here's a more detailed example: [ { "id": 1, "name": "PowerRanger", "description": "BLUE", "connections": [ {"id": 123,"meg ...

Get back a variety of substitutions

I have a variety of different text strings that I need to swap out on the client side. For example, let's say I need to replace "Red Apple" with "Orange Orange" and "Sad Cat" with "Happy Dog". I've been working on enhancing this particular ques ...