Sunday, November 22, 2009

jQuery: Shuffling Photo Gallery Tutorial

Creating a Shuffling Photo Gallery in jQuery is actually very simple. It's just a matter of calling timers("setIntervals()") and tweaking opacity.

Let's get started.

HTML
<div id="slideshow">
<img src="images/demo.png"/ class="active">
<img src="images/digg.png"/>
<img src="images/reddit.png"/>
<img src="images/twitter.png"/>
</div>
These are the images that you want to be shuffling.

CSS
<style type="text/css">
#slideshow{
text-align:center;
postion:relative;
}

#slideshow img{
position:absolute;
z-index:8;
top:0;
left:50%;
}

#slideshow img.active{
z-index:10;
}

</style>
We are gonna declare "position:absolute" for the images to stack up together.Z-index ensures that the "active" image will be on top of the rest.


Javacript
<script type="text/javascript">

$(document).ready(function(){
$('#slideshow img').animate({opacity:0.0},1);
$('#slideshow img.active').animate({opacity:1.0},1);
});

function slideSwitch(){
var $active = $('#slideshow IMG.active');
var $next = $active.next().length ? $active.next():$('#slideshow IMG:first');
$active.animate({left:'40%'},1000).animate({left:'50%'},1000).animate({opacity:0.0},500);
$next.addClass('active');
$next.animate({opacity:1.0},1000);
$active.removeClass('active');
}

$(function(){
setInterval("slideSwitch()",3000);
});
</script>

First, we hide all images except the active image.
$(document).ready(function(){
$('#slideshow img').animate({opacity:0.0},1);
$('#slideshow img.active').animate({opacity:1.0},1);
});


Next, our timer will call the function slideSwitch() every 3000 millisecond.
$(function(){
setInterval("slideSwitch()",3000);
});


In our slideSwitch function, we hook the active image into variable $active and the next awaiting image into $next.

var $next = $active.next().length ? $active.next():$('#slideshow IMG:first');

I found an excellent explanation from net-Tuts regarding the "?" above:

Think of everything before the question mark as being a question, if the answer to that question is true then execute the code to the left of the colon, but after the question mark. If the answer is false then execute the code after the colon.

The rest are just simple animation to mimic the shuffling action and also to reattach the active class to the images.

No comments:

Post a Comment