Sunday, May 15, 2011

How to make your background image as carousel using CSS and jQuery

This post will teach you how to set your background as carousel of images using CSS and jQuery.

To do this, just follow the 3 simple steps below.

1. First, you should have the list of images for your site's background.

2. Set an id for your <body> tag, let say id="body" as stated below.

<html>
<head>
</head>
<body id="body">
</body>
</html>

3. Create a javascript that changes the background-image property of the body tag using jquery and set it in a loop using setTimeout().

<script type="text/javascript">
        function carousel_bg(id) {
                var bgimgs = [ '1920x625_Sonata_homepage_image.jpg', '1920x625_Equus_homepage_image.jpg', '5_home_hero_1920x625_CF_background.jpg' ]; // add images here..
                var img = bgimgs[id];
                var cnt = 3; // change this number when adding images..

                $('#body').css("background-image", "url(http://www.pitstopmotors.com.ph/images/"+img+")");

                id = id + 1;
                if (id==cnt) id = 0;

                setTimeout("carousel_bg("+id+")", 10000);
        }

        $(document).ready(function() {
                carousel_bg(0);     
        });
</script>

You can still add images by adding the image filename on the array "bgimgs" and change the variable "cnt" to add images as part of the loop.. and that's it.

To get the complete code, please see below.

<html>
<head>
<title>Hotshots Carousel Background</title>

<script type="text/javascript" src="http://www.pitstopmotors.com.ph/js/jquery-1.4.2.js"></script>
<script type="text/javascript">
        function carousel_bg(id) {
                var bgimgs = [ '1920x625_Sonata_homepage_image.jpg', '1920x625_Equus_homepage_image.jpg', '5_home_hero_1920x625_CF_background.jpg' ]; // add images here..
                var img = bgimgs[id];
                var cnt = 3; // change this number when adding images..

                $('#body').css("background-image", "url(http://www.pitstopmotors.com.ph/images/"+img+")");

                id = id + 1;
                if (id==cnt) id = 0;

                setTimeout("carousel_bg("+id+")", 10000);
        }

        $(document).ready(function() {
                carousel_bg(0);     
        });
</script>
</head>
<body id="body">
</body>
</html>

14 comments:

  1. Simple and functional! I added:
    backgroud-position: center top in the CSS
    ;)

    I'll try starting a preload of this code and post it here ...

    Charles Costa from Brazil
    charles.costa@symean.com

    (Sorry for my English, I use Google Translator)

    ReplyDelete
  2. thanks charles.. really appreciate reading my post.

    ReplyDelete
  3. Hi Paul

    I have to create home page with background images rotation (carousel concept). if the user click any of the links in the home page. i have to set current rotating background image as a fixedbackground image for the session(until he close the browser).

    i want to do without jquery plugins. is there any code or site avialbale.

    regards
    ganesh

    ReplyDelete
  4. Hi Ganesh, sorry for the late reply but if that is what you want, you can actually use the script above but put a jquery script to clear timeout.

    Taken from the script above, set a variable that handles timeout, let say var t = 0; and should be place before the first call in carousel_bg(0).

    $(document).ready(function() {
    var t = 0;
    carousel_bg(0);
    });

    Then on the carousel_bg() function, you have to set the variable when setting a timeout, please see below.

    t = setTimeout("carousel_bg("+id+")", 10000);

    Then lastly, if you have a link, let say set to a class="link". you can put the jquery below inside $(document).ready() function.

    $('a.link').click(function() {
    if (t) clearTimeout(t);
    });

    Hope this helps.

    ReplyDelete
  5. can I easily add a fade effect to the image swap?

    thanks so much for this script!! it's a lifesaver haha

    ReplyDelete
  6. yes, you can.. just use fadeOut/fadeIn effect of jquery. goodluck!

    ReplyDelete
  7. Can you provide an example for the fadeIn()/fadeOut() usage? I can figure out how to use that in your loop for a block element, but not for a CSS property. Many thanks.

    ReplyDelete
  8. Hi Randy,
    Sorry for the late reply, been busy these days.
    Please try below.

    $('#body div#bground').fadeOut(function() {
    $('#body div#bground').css("background-image", "url(http://www.pitstopmotors.com.ph/images/"+img+")");
    $('#body div#bground').fadeIn();
    });

    Then create a div element inside the body with attributes below.

    id="bground"
    style="width:100%; height:100%; position:absolute; top:0; left:0;"

    Thanks.

    ReplyDelete
  9. This is superb, thanks. Is there anyway I can stop the whole page from 're-loading' each time an image changes? I am using the fadein addition, but the items (a navigation bar) fades in and out with each picture as well?

    Thanks

    ReplyDelete
  10. Please try setting up your background with z-index:-1; the whole page doesn't really reload. it only switches images.

    ReplyDelete
  11. Thanks for the post, very helpful! Inside the div that contains the background images, I have another div that I'm using as a hyperlink that corresponds to the background image. Is there way to swap the link with the swap of the background?

    If it helps get things across, this is my rough layout: http://sixfootgiraffe.com/100312/

    Thanks so much!!

    ReplyDelete
  12. Not sure if I get your question but you can add a new attribute on your link element like rel="the id of the image here" then create a javascript below.

    $('a.link').click(function() {
    var id = $(this).attr('rel');
    carousel_bg(id);
    });

    Hope this helps.

    ReplyDelete
  13. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. JPEG Optimizer

    ReplyDelete

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.