3

The default value for z-index is auto as based on MDN's documentation.

When I tried setting the z-index now to 1 like this:

$("body").css("z-index", 1);

And the retrieved the z-index property like this:

$("body").css("z-index");

it still returns auto.

Why is this happening and how can I retrieve the currently set z-index value?

Boaz
  • 19,892
  • 8
  • 62
  • 70
Richeve Bebedor
  • 2,138
  • 4
  • 26
  • 40
  • Try this maybe: http://stackoverflow.com/questions/7125453/modifying-css-class-property-values-on-the-fly-with-javascript-jquery – sshashank124 Mar 22 '14 at 11:31
  • I think your problem is related to the issue in [this post](http://stackoverflow.com/questions/8201855/cant-change-z-index-with-jquery). Basically, unless the element has an absolute, relative or fixed position you can't set the z-index. Not sure if you can make the body element positioned. – davidethell Mar 22 '14 at 11:32

2 Answers2

5

By default, z-Index doesn't work with position:static elements.

It only works with position:relative/absolute/fixed elements.

This might work:

elementSelector
{
    position:relative;
    z-index:1;
}

Reference: z-index - CSS-Tricks

Boaz
  • 19,892
  • 8
  • 62
  • 70
Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56
1

You need to set the position of the element then only z-index will work effectively...

check the jsfiddle

<div id="hello">deepak sharma</div>
<input type="button" id="set10" value="set zindex = 10" />
<input type="button" id="set20" value="set zindex = 20" />
<input type="button" id="get" value="get" />

$(function(){
    $("#set10").click(function(){
        $("#hello").css({"z-index":"10","position":"relative"});        
    });
    $("#set20").click(function(){
        $("#hello").css({"z-index":"20","position":"relative"});
    });
    $("#get").click(function(){
        alert($("#hello").css("z-index"));
    });
});

or you can set the position:relative in CSS also then there is no need to set the position in your jquery code.

jsfiddle

Deepak Sharma
  • 4,124
  • 1
  • 14
  • 31