Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196
News

Slideshow effects with jQuery

Slideshow effects with jQuery

Slideshow transitions with JavaScript using jQuery

jQuery is empowering JavaScript developers to do more than ever before. Used effectively, it can take your photo slideshows to the next level.

Let’s face it, JavaScript is making a huge comeback lately as developers find more ways to use it effectively for motion and effects. And the introduction of new frameworks for JavaScript, like jQuery (http://www.jquery.com), allows you to build rock-solid, cross-browser solutions that look and work every bit as good as Flash.

In this tutorial we are going to give a quick introduction to jQuery and present three different examples of transitions you can add to your next photo slideshow. We’ll start easy with a fade transition, work through an intermediate slide transition and end with an advanced ‘mask-type’ transition (‘mask-type’ because we are faking a mask as there are no real masking abilities in JavaScript yet). When you’re done here, you will clearly see the benefits of using a framework like jQuery for JavaScript, and should have a pretty solid grasp on what you can do in terms of some simple animation. Let’s get started…

Project files for this tutorial can be downloaded here.

This article was originally authored by Matt Wiggins, and featured within Web Designer issue 165

01 You’ll need jQuery

step-1

The first step is to download jQuery, a framework built to simplify and speed up JavaScript development. If you’re new to jQuery, you may want to take a minute and go through the basic tutorial. The latest version can be found at the website (http://www.jquery.com) and it’s worth visiting to make sure you have the very latest version.

02 Setup folder/images

step-2

Set up a folder structure for your project. We kept it simple and created an XHTML file for each example, a folder for our photos, and included jQuery in the root folder of the project. When your folders are set up, choose a set of photos and re-size them so that they are all the same size.

03 XHTML

We will use a simple XHTML structure that includes the same elements across each example. You will need a main wrapper to add some padding, a frame for the photos that hides overflow and adds a border around the images, next/previous buttons and a transition container that will hold the images/mask. As with many of these steps, the full code can be found in the project files.

<div id=”wrapper”>
 <div id=”frame”>
 <!-- photos -->
 <div id=”transition-container”>
 <img class=”photo” id=”photo-1” src=”images/photo-1.jpg” alt=”photo one” />
 <img class=”photo” id=”photo-2” src=”images/photo-2.jpg” alt=”photo two” />
 <img class=”photo” id=”photo-3” src=”images/photo-3.jpg” alt=”photo three” />
 <img class=”photo” id=”photo-4” src=”images/photo-4.jpg” alt=”photo four” />
 <img class=”photo” id=”photo-5” src=”images/photo-5.jpg” alt=”photo five” />

04 CSS

There are a couple of important things to note for CSS. First, each div in the structure needs to have its position property set to relative so it can be animated. Also, the frame div needs to have its overflow property set to hidden because it serves as a mask for the photos. Pretty much everything else is flexible, see the example for further help. The full code for this step can be found in the project files, titled step-4.txt.

#wrapper
 {
 padding:20px;
 }
 #frame
 {
 position:relative;
 width:600px;
 height:450px;
 background-color:#000;
 border:5px solid #000;
 /* serves as a mask */

05 Start simple with a fade

step-5

Let’s start simple with a fade transition between photos. Fading is really simple with jQuery as it has built-in functions fadeIn() and fadeOut(). Include jQuery on the page with a script tag. Then, create another script tag to place your code.

<!-- include jQuery (http://www.jquery.com) -->
 <script type=”text/javascript” src=”jquery-1.3.2.min.
 js”></script>

06 Required global variables

step-6

We’ll need a few global variables to track various items within the slideshow. First, and most importantly, we need to store the id of each image in an array. This way they are enumerated and accessible from anywhere. Also, add a variable for the selected photo (number) and a transition lock (boolean).

var arrPhotos = new Array(‘#photo-1’, ‘#photo-2’, ‘#photo-3’, ‘#photo-4’, ‘#photo-5’);
 var selectedPhoto = 0;
 var transLock = false;

07 jQuery $(document).ready

Next, use a jQuery event listener to listen for the DOM to be ready. This event fires when all of the containers on the page are rendered and ready to accept code. Inside this listener we will set up our Next/Previous buttons and transition our first photo in. The full code for this step can be found in the project files.

// DOM is ready, let’s get started!
 $(document).ready(function() {
 // init prev/next buttons
 $(‘#btn-previous-img’).click(function() {
 if(transLock) return; // ignore request if a transition is already happening
 else transLock = true; // otherwise lock it so requests are ignored until this transition is complete
 // fade old photo out
 $(arrPhotos[selectedPhoto]).fadeOut(‘slow’, function(){
 // fade new photo in selectedPhoto--;

08 Fade images in

step-8

The only other function we need for the fade transition is moveToImg(). This method takes an id parameter and fades the selected photo in. After the photo is faded in, a callback is used to unlock the transition, we’ll go into this in a minute. Also, notice that this method is called at the bottom of the DOM ready listener to fade the first photo in.

function moveToImg(id)
{
 $(arrPhotos[id]).fadeIn(‘slow’, function(){
 transLock = false;
 });
 }

09 Previous button

step-9

Now we need to set up our buttons. We’ll do this with a jQuery click event listener. Check the transition lock and lock the transition. This way, clicks will be ignored until the current transition finishes. Then fade out the old image and use a callback to set the new image and call moveToImg() to fade it in. The full code is in the project files.

$(‘#btn-previous-img’).click(function() {
 if(transLock) return; // ignore request if a transition is already happening

10 Next button

The Next button basically works the same way, except it increments the selectedPhoto instead of decrementing it. Remember the callback in the moveToImg() function? It is used to unlock  the transition lock set in these listeners.

$(‘#btn-next-img’).click(function() {
 if(transLock) return; // ignore request if a transition is
 already happening
 else transLock = true; // otherwise lock it so requests
 are ignored until this transition is complete
 // fade old photo out
 $(arrPhotos[selectedPhoto]).fadeOut(‘slow’,
 function(){
 // fade new photo in
 selectedPhoto++;
 if(selectedPhoto > arrPhotos.length - 1) selectedPhoto= 0;;
 moveToImg(selectedPhoto);
 });
});

11 Don’t go too far

step-11

One other thing to note is that in both button listeners you will see code that checks the value of selectedPhoto and loops it around to the end or beginning if it gets too high or low. Storing the photos in an array is very important for this step.

selectedPhoto--;
 if(selectedPhoto < 0) selectedPhoto = arrPhotos.length - 1;
 selectedPhoto++;
 if(selectedPhoto > arrPhotos.length - 1) selectedPhoto = 0;

12 Test/Preview

step-12

That’s it! You’re done with example one. You should now be able to preview your progress. If you have any issues, simply cross reference your work against the example that is provided in the project files. From here, you can try adjusting the speed of the fade transition to get the effect you are after.

13 Example two: slide

step-13

Next, let’s move it up a gear and on to an intermediate level slide example. For this transition, we will float our images inside a container in our frame (remember, it is set to overflow hidden) and use jQuery to animate the left property of that container to create a perfectly seamless sliding effect.

14 Slide setup

There are a few differences in the setup from the last example. First, change the CSS on the photo style so they are floated left. Also, adjust the transition container so its width is the sum of all the images in the slideshow. Finally, check that the frame is set to overflow hidden.

#transition-container
 {
 height:450px;
 /* should be the sum of all photos */
 width:3000px;
 /* position it */
 position:relative;
 top:0px;
 left:600px;
 }
 .photo
 {
 float:left;
 }

15 Function to slide images

We are able to use most of the same code from the previous example here. One of the key differences is that now the moveToImg() function is animating the position of our transition container. jQuery’s animate method can be used to animate almost any CSS property of an element. In this example, we are animating the left property to a negative value relative to the respective x of the selected image.

function moveToImg(id)
{
$(‘#transition-container’).animate({‘left’: -(id * 600) +
 ‘px’}, 750, ‘swing’, function() {
 transLock = false;
});
}

16 Next/Previous buttons

step-16

Both the Next and Previous buttons for this transition work almost exactly the same as in the previous example, except that there is no real need for an out transition this time around. So, they simply lock the transition, set the selected photo and then call the function to move to the new image.

17 Test/Preview

step-17

That’s it! You’re done with example two. You should be able to preview your progress. If you have any issues, cross reference your work against the example provided in the project files. From here, you can try adjusting the length of the animation and for nicer easing, check out the plug-ins directory (http://plugins.jquery.com).

18 Example three: masks

step-18

Finally, let’s step it up again to an advanced example.
This example will use a fake mask to build a block transition. It’s a fake mask because it is simply a div or image that is the same colour as the background colour of our frame that we will manipulate by fading or moving.

19 Mask setup 1

step-19

We’ve got a few changes to make to XHTML/CSS before we continue. First, we need to set up styles for the transition blocks (each square in our mask). They should be floated left, the same colour as your frame background and you can choose the width and height as long as they will fit exactly over the images.

20 Mask setup 2

Next, we need change the transition container to be position absolute at 0, 0 and the same width and height as the photos. Then in the markup, we need put it on top of the photos. The photos should also be changed back to their original style from example one. The full code for this step can be found in the project files.

#transition-container
 {
 height:450px;
 width:600px;
 /* position it */
 position:absolute;
 top:0px;
 left:0px;
 }
 .photo
 {
 position:absolute;
 top:0px;
 left:0px;

21 Initialise blocks

You’ll notice that, once again, our code looks pretty similar to previous examples. Let’s go over the differences. First, in the DOM ready event listener you will notice a loop that creates and adds several divs to the transition container. The number of divs to add is calculated by figuring out how many will fit based on their size.

// init block mask
for(var i = 0; i < 30; i++) // 108 is the number of blocks
 (50x50 blocks 12 wide, 9 high)
{
arrTransBlocks[i] = ‘#transition-block-’ + i;
$(‘#transition-container’).append(‘<div id=”transition-
 block-’ + i + ‘” class=”transition-block”></div>’);
}

22 Randomise and fade

Now that we’ve added a bunch of sequential divs, we need to randomise them and fade them in or out in one after another. We do this with a function to randomise our array of blocks and recursive functions to fade the blocks in one after another. These recursive functions recall themselves if the number of blocks faded is less than the number of blocks, essentially creating a loop. The full code for this step can be found in the project files.

function executeTransIn(num, speed)
 {
 if(num < arrTransBlocks.length)
 {
 $(arrTransBlocks[num]).animate({opacity:0}, speed,
 ‘linear’, function() {
 executeTransIn(num + 1, speed);
 });
 } else {
 transLock = false;
 }
 }

23 Test/Preview

The way the buttons and everything else works is all pretty much the same in this example. They set the selected photo, call executeTransOut() which recurses until each block is faded in then calls executeTransIn(). From here, why not experiment with different masks?

×