Chris Cummings
Chris Cummings

Reputation: 1548

Change z-index infinitely in jQuery

I am a bit new to jQuery but I need to write a small custom image rotator. Basically I will have a small stack of .png images that look like Polaroids. The rotator will need to pull the top one off, move it to the right, set the Z-index lower than the other two, then move it back over...just like you would if you were looking through a stack of pictures.

Most of this I think I can do, but the problem I'm not quite getting is that I will need to continually swap the Z-index of these 3 images (move top image to right, reset z-index lower than the other two, move back)

In the HTML I have the following:

<img src="images/polariod_1.png" width="255" height="260" alt="Singer" class="headerrightgraphic">
<img src="images/polariod_2.png" width="255" height="260" alt="Singer" class="headerrightgraphic">
<img src="images/polariod_3.png" width="255" height="260" alt="Singer" class="headerrightgraphic">

Any leads on how I can change the z-index on these in an elegant way without hard coding it over and over?

Upvotes: 1

Views: 218

Answers (4)

kamchatka
kamchatka

Reputation: 127

I would consider using display:none / block instead of changing the z-index. Z-index image galleries have cause me nothing but trouble in the past.

Here is a snippet I found on google. Source

$(function(){
$('.fadein img:gt(0)').hide();
setInterval(function(){
  $('.fadein :first-child').fadeOut()
     .next('img').fadeIn()
     .end().appendTo('.fadein');}, 
  3000);
});

Upvotes: 0

falsarella
falsarella

Reputation: 12447

What about to use display:none; in the images behind, that can't be seen?

Upvotes: 0

JakeJ
JakeJ

Reputation: 1381

I would say to store the values in a global variable in your JS, use the .data function in jquery or use some hidden inputs to hold the current z-index.

You could also try and not use z-indexing and maybe manipulate the positioning of the elements (elements 'lower down' in the dom tree will appear on top of others), so maybe move it to the site, prepend it to the first img, and then slide it back into place.

Upvotes: 0

Dagg Nabbit
Dagg Nabbit

Reputation: 76756

Instead of changing the z-index, consider giving all the photos the same z-index and reattaching them to the parent node in the order they need to display. This removes the need for "infinite" z-indexes to get content above and below the photos.

For example if the user can click one to pull it to the top, just re-append it to the parent node:

// assuming you have a handle to the element `photoElement`

photoElement.parentNode.appendChild(photoElement);

Upvotes: 1

Related Questions