Fazil Mir
Fazil Mir

Reputation: 833

How to change zIndex of an element on click in jquery?

I want to change z-Index on button click. I have a static image and a dynamic div. Now I want to send the #imgDiv1 behind the static image. But I don't know how to do this. I tried everything but all in vain.

Here is the live demo. jholo.com I want to implement this concept in this web application.

Here is my mark up

<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"/>

jQuery

 $(document).ready(function(){ 

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

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

});

This is what i want

Upvotes: 2

Views: 11311

Answers (2)

Sai
Sai

Reputation: 1949

I used opacity instead of z-index... is that 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);
});

the js fiddle link is.. http://jsfiddle.net/6rwBR/ hopefully this helps

Upvotes: 0

jfriend00
jfriend00

Reputation: 707686

The z-index style property only takes affect on elements that are not position: static. So, you will need to set the position property before you can see the impact of z-index.

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>

CSS:

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

Code:

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

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

Working demo: http://jsfiddle.net/jfriend00/5Efm3/


Edit - Responding to your additional edit:

To achieve the effect you're looking for, you will also need the snowflake like image to have transparency inside the snowflake shape thus allowing the behind image to show through which means it can't be a JPG,. It could be GIF or PNG.

Upvotes: 5

Related Questions