Smooth fullscreen background slideshow in jQuery

Coding
By Jasper | October 3, 2010

After having a look at a variety of fullscreen slideshow effects in jQuery, I figured this could be done smoother (by waiting for images to actually load before displaying them and adding an optional grid) and in only a few lines of code. I use this effect for displaying a slideshow of images on the background of this blog and I cleaned op the code for anyone’s enjoyment. In this article I will walk through my ideas for anyone who’s interested in using this effect.

Click here to see the end result | Click here to download the source

Basic HTML structure

The goal of this effect is to display the slideshow in the background, without interfering with the actual content of the website. The following document structure will take care of this:


<body>

<!-- This is the main page -->
<div id="page_overlay">
 <div id="page_content">
 Actual page content
 </div>
</div>

<!-- The container for the description -->
<div id="image_description">
 <span id="image_artist"></span><br/>
 <a id="image_url"></a>
</div>

<!-- The container for the background-image -->
<img id="bg" style="display:none" />

<!-- The container for the grid on top of the background-image -->
<div id="bg_grid">
</div>

</body>

The page content will be added to the section page_content. This section needs to be on top of the background and the background grid. The background grid (div with id bg_grid, which will contain a transparent .png existing of a single visible pixel and three transparent pixels) is put on top of the background image (img with id bg).

This stack is achieved by using fixed positioning on bg_grid as well as bg and giving bg_grid a higher z-index than bg. Furthermore, page_content needs to be positioned relative to make it float over the background and be flexible enough to contain any content you wish. The following CSS takes care of this all:


#page_content {
 /* Display on top of slideshow */
 position:relative; /* This is very important! */
 z-index:2;
}

img#bg {
 /* Stretch background */
 position:fixed;
 top:0;
 left:0;
 height:100%;
 width:100%;
 z-index:0;
}

#bg_grid {
 position:fixed; /* This is very important! */
 top:0;
 left:0;
 height:100%;
 width:100%;
 background: url(grid.png) repeat;

 /* Display on top of background */
 z-index:1;
}

As you can see, the background is stretched simply by setting width and height to 100%. This works beautifully for landscape images, but may be disturbing if your images are portrait. This code will not solve that for you. The grid on top of the image can easily be turned off by deleting the background from #bg_grid.

Script for fading the background images

As promised, I will only use a few lines of code to make the magic happen. In the first part of the script, I define three arrays (aImages, aURL, aArtists) that contain the links to the images, the related URLs (that will be displayed in the description) and the related artists (also displayed in the description section). I will leave the array definitions out for now, as you can easily look these lines up in the example code. The core of the functionality is:


$(document).ready(function() {

	/* Define the function that triggers to fade in the background */
	$("img#bg").load(function()
		{
			/* Fade in during 3 seconds */
			$("img#bg").fadeTo(3000,1);

			/* Animate the picture description during 1 second */
			setTimeout(function()
				{
					$("#image_description").animate({right: '+=150'}, 1000)
				}, 1000);

			/* Set the timeout to fade out after 10 seconds*/
			setTimeout(function()
				{
					$("#image_description").animate({right: '-=150'}, 1000);
					$("img#bg").fadeOut(3000);

					/* Load the next image after 4 seconds */
					setTimeout(LoadImages,4000);
				},10000);
 		});

	/* Start the slideshow one second after the page is ready */
	setTimeout(LoadImages,1000);

});

function LoadImage(iNr)
{

	/* Assign the new image to the background */
	$("img#bg").attr("src", aImages[iNr]);

	/* Assign the artist name to the description */
	$("#image_artist").html(aArtists[iNr]);

	/* Assign the image url to the description */
	$("a#image_url").attr("href", aURL[iNr]);
	$("a#image_url").html("for sale @canvasinabox.com");

};

function LoadImages()
{

	/* Select a new random image number */
	while(iPrev == iRnd)
	{
		iRnd = Math.floor(Math.random()*aImages.length);
	}

	/* Show the selected image */
	LoadImage(iRnd);

 	iPrev = iRnd;

};

To start the fade in, we add a handler with a function to the bg image element. For this we use the load event (in line 4) which triggers its handler after the image has been loaded into the browsers memory. This is very important, because the image will most likely not fade in smoothly if it’s not already loaded or in the browsers cache. The fade in may be half way or already completed before the image is loaded, which we don’t want. This function will also take care of animating the description and triggering the fade out after 10 seconds.

In line 27 we tell the browser to run LoadImages for the first time, one second after the page is ready. LoadImages (which starts on line 46) selects a random image number and makes sure this is not the same number as the image that was displayed before. It feeds this number to the LoadImage function (line 31) that actually loads the new image (thereby triggering line 4 when ready!).

Finally, the next image is loaded in line 22, four seconds after the fade out was started (which takes three seconds to finish). That’s all there is to it. Feel free to download the source and use these ideas for your own projects.

69 comments on “Smooth fullscreen background slideshow in jQuery”

  1. Thanks Jasper! Great work here.

    The above source link takes me to the demo, was that your intent or did you mean to point to an archive file perhaps? Thanks again.

    //Frankie

    • Hi Frankie! Thanks for your message. You’re absolutely right, I should have pointed this link to the source archive. Fixed it now.

      Cheers,
      Jasper

  2. Could you have a default first image that initially loads while the others are loading?

  3. The images are actually loaded in order and displayed after the load of a single one has completed. So, first the first image is loaded and displayed, second the second image is loaded and displayed, then the next, etc.

    Displaying of the first image is intentionally delayed by 1 second to increase the dramatic effect, but you could display it as soon as the page is completed by replacing the setTimeout in line 27 (in the code above) by a direct call to LoadImages(); – this will display the first image as soon as possible.

    Does this answer your question or did you have something else in mind?

  4. This is great! Are you planning an option for fixed image ratio in the future? I couldn’t work it out…

  5. Hi Christoph, thanks for your reponse. This is – of course – a good idea. As soon as I find some time for it, I will certainly give it a try…

  6. Hey, first of all i want to say that this looks absolutely incredible!
    im having a few issues making it work for me though, im not professional but im not exackly new to it either.
    so iv grabbed the source, iv saved the grid image twice. first one titled bg_grid, and second one is named bg. its all in the same folder, but when i hit f12 in dreamweaver, my page preview loads with the bg dotted image and the black heading, but the images don’t ever load, it just sits on the dotted screen forever.
    iv tried a number of things for the past few nights but id really appreciate if you could tell me what im doing wrong as none have succeeded yet.
    thanks a heap

  7. No problem, happens to me all the time. Good to know you solved it. :-)

  8. 10 Michelangelo November 24, 2010 2:46 am

    Hi, Jasper

    If you can help me get this on my blog, I’ll be so grateful. I have a Blogger account (free) and I would love so much to have this on my blog.

    Please can you help me by directing me a little about where to place which coding in my html.

    It really would mean a lot to me.

    Many thanks

  9. 11 Michelangelo November 28, 2010 2:07 pm

    Please try to help me, I’ll really appreciate anything you can tell me

  10. @Michelangelo: I’m not sure about how Blogger handles HTML and CSS code in its templates, but if you’re able to edit the HTML file, you could easily put all style and script code in the header and the divs in the body. Just have a look at the code in the demo and notice where the script- and style-parts are located (in the head-section) and where the divs are located (in the body-section). It should be the same in your blogger template.

    The existing page in your template should go in the page_overlay div-section, this way the page is displayed on top of the background. Also make sure that the existing page doesn’t have a background, because this will cover the slideshow.

    I hope this helps.

  11. 13 Michelangelo December 7, 2010 1:41 pm

    Thank you very much! I will experiment and try to figure it out.
    God bless

  12. Thanks for this great script.
    Any suggestions on how to add the images as a background in stead of a div??

    Thanks

  13. hi jasper, nice work on this – probably the simplest solution for this effect I’ve found so far. I have one suggestion and also one question!

    question – works fairly well in FF, but pretty much stalls out the browser in IE(7) on XP. Have you experienced this too or do we simply need to wait for IE 9 or just upgrade to IE 8?

    suggestion – amending the css slightly can give you the FIXED RATIO for background images, so they don’t appear stretched – i’ve tried this on your page too and it works! simply use these settings for the img#bg css:

    img#bg {
    /* Set rules to fill background */
    min-height: 100%;
    min-width: 1024px;
    /* Set up proportionate scaling */
    width: 100%;
    height: auto;
    /* Set up positioning */
    position: fixed;
    top: 0;
    left: 0;
    }

    regards,
    dk

  14. Looks lovely on my MacBook. I will test tomorrow on an old PC we have in the studio and post the results.

    Have you thought about adding controls for the slide show so you could select images or links?

  15. @DK: Thanks for sharing your ideas and sorry for my late reply. On Windows, I’ve only tested this in IE8. I notice in any browser that the performance depends mostly on the window size. I tried it in a VirtualBox installation on Windows 7 on my Mac and it’s still smooth (more or less :-) ).

    @Jamus: This effect is intended to run in the background of a website (typically not interactive). But it should be not too difficult to add controls. Because of other projects, I will not be doing this any time soon, maybe someone else will share a solution?

  16. @Martijn: I missed your message, sorry for that. Actually, the image itself is not in a div. The divs are used to put content on top of the image. I don’t think this effect can be achieved using the CSS background property – if that’s what you meant (unless we put the background on a div in which case the img-tage is probably more convenient anyway).

  17. Hello and thanks for the lovely code. I was just wondering if you have the time to explain how I might deploy this slideshow in a WordPress blog similar to what you’ve done. I’m fairly new to header and footer PHP files, but I’m sure that is where your code should go. Feel free to contact me on my personal email.

    Cheers

  18. Hi, your code has saved me so much headaches. Thanks so much.

    As a newbie I am struggling with trying to tweak this a bit.

    I cant seem to figure out how to make the transitions seamless.

    Is there anyway way to load the next image before the previous one fades out totally.

    Thanks

  19. Hello, thanks so much for posting this. It’s exactly what I needed and the overlay grid adds a nice touch. I’m new to this and I have two questions.

    1. I got the slideshow to work but a white box is always shown in between each loaded image, is there anyway to get rid of this?

    2. This is probably pretty ignorant, but how can I change the links to the files in my image folder? I tried and ../images/ link but it’s not working.

    3. Oops maybe 3 questions, my grid isn’t showing up but the script hasn’t been changed? Any recc?

    Thanks so much!!!

  20. Just to clarify, I’ve gotten the grid to show up but I was wondering about how to create a root relative path the the images rather than an absolute one.

    Thanks!!!

  21. The height isn’t 100% in IE 6 does anyone have a fix for this?

  22. On one page I just want 1 image. No fading or switching images. Also on the pages with the fading and switching, the images fade to the background color. How do I make it so they fade to the next image and the background color never really shows through?

    Thanks in advance!

  23. hey Jason,

    Awesome work and thanks for sharing. Need some advice.
    The images do not match the height and width of the browser proportionally. Any advice?

  24. hi! goooood work! only a question! It’s possible to disactivate the random load image? Can i load a sequency list of images?

    thank you so much!

  25. have u seen your page in ie6??

  26. @Peter & Brandon: Sorry, this is not possible using this approach. It doesn’t buffer a second image upfront. I know there are other scripts that demonstrate this.

    @Satheesh: This was my intention. Refer to response #15 (DK) for a proportional solution (haven’t tested this, but it looks good).

    @Mark: The simplest way would be to change the LoadImages() function. Use a global var as a counter, increase it in LoadImages() and pass it to LoadImage().

    @Atze: Sorry, I can’t be bothered by IE6, it’s is too outdated.

    This code is just a starting point, use it for experimenting and try to improve it. :-)

  27. Hi, how can i change the code to display only one slideshow/image and after fade in and shows the pic it stop directly, without fade out and reload new image?? please advice… thanks

  28. @Ara: Try removing lines 15 to 23.

  29. 32 christian June 14, 2011 8:06 am

    hi jasper,

    great work. Was wondering the liscencing of the code, and if you grant it to be used for template creation.

    thanks

    christian

  30. hey jasper, no worries about the proportional code – it’s still working fine for me across most browsers. I have a problem though – I’m running 9 images through the script (all at the same resolution / dimensions), and every so often (completely randomly) one of the images won’t show up – the background will be blank. It happens with different images, as I say, in a completely random pattern, perhaps one every 10 images or so. The description tab still appears even though the image does not… fading into the next image works fine until the problem occurs again later down the line.

    Have you experienced this yourself, and if so do you have a fix?

  31. Is it possible to load images from a folder instead of writing out each image’s absolute path?

    thanks
    Andrea

  32. @Christian: that’s ok as long as the credits remain as is. Thanks :-)

    @DK: I’ve not experienced this myself and I can’t think of a reason why this would go wrong, because all this script does is repeat itself over and over. So, very strange indeed. I’m sorry that I can’t help you with this problem. Does it happen in all browsers (I use Firefox most of the time)?

    @Andrea: You would need a server side script (i.e. PHP) to fill your array, as this can’t be done through javascript only (browsing through folders on the server). As an alternative, you could number you images 1 through n and use a javascript loop to fill the array (without requiring server side input).

  33. @JASPER: well I’ve done some more testing on the problem, and spent a long time comparing your script and the changes I’ve made in my implementation. In the end I just had to sit back and watch the slideshows to see a bit better what was happening. Turns out the speed of the transitions is what upsets my slideshow – most notably, I think, is the command line:

    setTimeout(LoadImages,4000);

    it seems that if you reduce the interval times as I had done for loading one image after another (this could also be the fade-in or fade-out times), for some reason the script can’t keep up (even though I have the images cached / preloaded). I’ve been watching the code and when an image doesn’t load, I get the following html:

    <img id="bg" style="display: none; …etc rather than the display: block;" I usually receive.

    I don't know why this is the case, or why it only happens roughly every 7 or 8 slides, but slowing down the transitions allows the slideshow to function without any problems. If by any chance you could look into this issue and provide a possible solution it would be HUGELY appreciated. (I test on Chrome, Firefox and IE 7/8).

  34. @DK: The problem is probably that if you decrease the setTimeout (which is 4 seconds) on line 22, it may trigger before the fade has ended (on line 19). Both the fade and the animate (line 18) are asynchronous actions (which means that the script continues without waiting for it to finish). That’s why the time-out is set to 4 seconds to make sure the fade is finished (and have 1 extra spare second). So… if you decrease the timeout, you should speed up the fadeout (by decreasing the value 3000 in line 19, which should always be lower than the timeout). Hope this helps!

  35. hi, thanks for this amazing script
    but i want to say is there a way for me to fade-in and out images without the “blank” time?
    what i mean is i have to wait the image from fade-in and fade-out every single time, what if i can manage it a photo which are fading-in and the next is ready without showing the blanked background. by overlapping the fade-in and fade-out time
    thanks

  36. Hi Soun, crossfading is currently not possible with this script. I know there are scripts around that can do this. With my script it would be a matter of copying part of the code (so two divs would be used to load images) and good timing (load one image while displaying the other one). I’m not sure if this would be the best solution though.

  37. Hi, im trying to use this effect for a fashion website. I have changed the images in the aImages variables to images from my images folder in my local site.

    e.g.

    aImages [0] “images/bg_images/fashion_face_1.jpg”;

    But for some reason after a while at random, it fails to load an image and the background remains white. All ive done is change the image links that were originally there to my own from my local website folder.

    Any idea why it goes blank? thanks :)

  38. ok i have changed the display:none to display:block, and it seems to prevent the failed loading of the random image. However, i now have the issue of the 1st image which is loaded just appears suddenly rather than fade in, because of the display:block attribute on the background. Any way to prevent this?

  39. woops scrap that the display:block didnt help. For some reason the failed load happens at random on different images, no idea why :S Any help would be appreciated greatly :D thanks

  40. Hi, first off, thank you for a great tutorial Jasper. This is exactly what I was after.

    I was wondering if you could give a novice a few tips. I’m interested in disabling the random image generator and wanted it to be sequential, I know someone asked this earlier but I wasn’t too sure how to go about creating a global variable as a counter. Is there any advice you could give to go about doing this? My jquery knowledge is fairly poor at the moment, I am learning though.

    Thanks very much for your help in advance.

    James

  41. Awesome slider! One of the best out there ;)

    I’ve changed the css a bit so it scales the images nicely. The only thing I want now is that the next image fades on top over the other. Could anyone tell me how to get this done?

    Thanks allot!

  42. Hello, Jasper!
    Tell me please, is a setTimeout (LoadImages, 4000), the maximum time?
    The limit of a good script?
    Thanks in advance!
    ded-pikto

  43. hi, thanx for the tut, it was very day to follow and do, and I’m pretty new at this stuff, just wondering though, how do u link the script code into a separate .js file? if that makes sense….
    thanx:P

  44. dw, figured it out, thanx anywaiz… :D

  45. hey, great tut, but how do i apply text over the slideshow without it fading away every time the next image appears. I would like to place text on top of the images without having a solid box/wrapper under it.
    any suggestions, thanx

  46. SOMEONE. Try the second background, with the function of transparency and the text.
    JASPER. Figured out myself, thank you …

  47. @DED-PIKTO and others: sorry for not responding instantly, other priorities are pushing. To my experience, most questions can be answered by Googling and experimenting a bit (which is part of the fun of developing a fine piece of code anyway! :-) . Enjoy!

  48. @SOMEONE: Could this be solved by choosing the right color for your font and disabling the background in your #page_content? Is that what you’re looking for?

  49. Hi, any updates about the white background pauses?
    regards,

  50. Hi, this is a cool plugins but the pauses between images are annoying, any updates about crossfading effect for the images??
    regards,

  51. Hi There

    I am using SquareSpace to create my site and i was hoping to use this script. I am a complete novice.

    Where should I place what code into my Header Tag and what should I place into my body tag. Should I add any custom css? Any help would be much appreciated.

    Cheers

  52. Hello Jasper,

    Great tut, i’m new to this, wanted to ask you how can i make the images fade in order(1,2,3…), i tried to remove the last function which makes them fade in a random way but with no luck.

    thanks in advance

  53. Anyone figured how to add a button that triggers the next image?

    I want this effect, but don’t wanna steal it…
    http://www.upstruct.com/

    Hope someone can help

    A

  54. 60 Marcelo de souza November 11, 2011 5:43 pm

    Obrigado era isto mesmo que estava procurando. valeu!!!

  55. Really great tut! Been searching for a while, and it’s the best so far! Thanks.

    I’m having a prob. though. I’m using it on a web design exported from photoshop, and I need the table position to be fixed, and not float its cells to 100% of the page. Changed all the positions to either absolute or fixed, but still the cells float on the page, how do I keep them in one place?

    Thanks a lot,
    L.

  56. Hello Jasper,
    I inform you that on internet explorer 9 and safari doesn’t work, windows 7.

    Alex

  57. Thank you for the great script and the clear tutorial.. I have followed the example file and managed to get it runnning on one of my clients websites.

    You can view it here (only on home page)…

    http://justinyap.com/

    Thank you so much for making this available … Great work!!!

  58. Thanks Jasper for the script!
    I wonder is it possible to have kenburns effect for the transitions.. how to implement it?

  59. Hey everyone :) How can I make the background images cross fading? I just want to avoid this delay after and before image, thanks in advance

  60. thanks dear it’s very nice

  61. Hi Jasper

    I would just like to say that your tutorial is amazing and I really appreciate you sharing your code. I’m a bit of a novice when it comes to web design so please excuse me if this question sounds stupid but how do I make my site content stay in a fixed position on the page (much like the way this site works. Hope that makes sense!

Your comment