Nicolas
Nicolas

Reputation: 2814

jQuery show and z-index

The following code is not working as expecting :

EDIT:
Sorry for the misunderstanding, I simplified too much my issue, here is the real issue I'm facing: http://jsfiddle.net/bc6hr/


HTML:

<div id="1">div 1</div>
<div id="2">div 2</div>

CSS:

div {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    background: white;
}
#1 {
    z-index: 2;
}

JS (jQuery):

$("div").hide();
$("#1").show();
$("#2").show();

I must be missing something, because from what I know, this code should be displaying "div 1" fading to "div 2", but it is actually rendering "div 2" from the start.
How could I make it displaying "div 1" knowing that I must hide all divs before? I thought using z-index was a good try, but maybe I'm wrong...

Upvotes: 0

Views: 1438

Answers (4)

Boldewyn
Boldewyn

Reputation: 82784

The problem is, that 1 and 2 are not valid IDs. Therefore either jQuery or the CSS parser doesn't recognize the element. Use a and b instead and see it working: http://jsfiddle.net/mBWcM/1/

The problem is, that when you call the z-index change in JavaScript, the divs are not even there (the code lives in the head element and is immediately executed). See the fiddler page's source.

Work around: Embrace everything in the "Start, when DOM is ready" construct:

jQuery(document).ready(function () {
   // your code here
});

Edit: Actually, I think it's a jsFiddle issue. When I re-load the page once or twice, it happens, that "div1" remains visible, the other times, it's "div2". I just saw, that jsFiddle indead wraps the code in a window.onload equivalent.

Upvotes: 0

nonopolarity
nonopolarity

Reputation: 151126

I believe the id cannot start with a number. When the div's ids are changed to d1 and d2, they work:

http://jsfiddle.net/mBWcM/4/

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196187

Change your IDs to valid ones ... (no starting with numbers)

example http://jsfiddle.net/mBWcM/3/

Upvotes: 0

rahul
rahul

Reputation: 187090

First of all your id attribute is invalid. You cannot start an id with number.

Updated your jsfiddle.

Upvotes: 2

Related Questions