jQuery Unobtrusive Background Image Switcher

Since our MooTools class worked well on many projects we went ahead and rewritten it for jQuery (after all it’s a jQuery world out there).

The idea as well as functionality remains pretty much the same: we need to use as many (probably background) images as we want no matter how heavy they are, while minimizing their influence on load times.

Here are the basic requirements:

  • Only the first image has to be loaded, the rest must “wait for their turn” and load as needed.
  • The image has to be preloaded and only shown after the load is completed. We now use fade effect for every image including the first one.
  • Support for responsive full screen background feature without breaking the image’s proportions on any screen/window size.
  • It has to be lightweight and play well with other front end features.

So here is the jQuery version:

No need to pass the full screen option any more, for jQuery version of this plugin it is handled entirely by the CSS – again if you want the full screen feature to work, download the whole package and take a look at our bare bones style.css. The CSS part is based on Perfect Full Page Background Image / CSS-Only Technique #2 from css-tricks.

Images used in this demo are copyrighted and only intended for this demo.

Further information, usage and options:

To use the plugin include jquery.bcat.bgswitcher.js as well as jQuery framework and initiate it like this:

<div id="bg-body"></div>

<script type="text/javascript">
// array with image paths 
// you can hide it within the scope 
// and use your back end system to generate it
var srcBgArray = [
  "/path/to/image1.jpg",
  "/path/to/image2.jpg",
  "/path/to/image3.jpg"
];

$(document).ready(function() {
  $('#bg-body').bcatBGSwitcher({
    urls: srcBgArray,
    alt: 'Alt text'
  });
});
</script>

Use any element as the container for the images and call the plugin from this element (div with id “bg-body” in this example). Everything including the array with image urls is passed as an options object, obviously you have to pass at least the urls array, the rest is optional:

  • urls – array with image paths, should it only contain one item the script will run as an image preloader, further functionality would not be initiated. Defaults to an empty array, has to be passed
  • startIndex – integer array element (index) to start with, defaults to 0
  • timeout – integer timeout in milliseconds, defaults to 12000
  • alt – string text to fill the alt attribute of each image, defaults to ‘Picture’,
  • speed – integer animation speed in milliseconds, defaults to 1000
  • links – boolean if the navigation links have to be shown, defaults to false

This plugin was written for jQuery 1.9 but it works with jQuery 1.2+ (wasn’t tested with earlier versions, might also work). Plugin structure is based on jQuery Boilerplate.

Browser support: IE8+ and other browsers that are not too old.

Again feel free to leave comments, send feedback messages and share this page, your reaction really motivates us.

Updated to v. 1.1: added support for multiple instances per page.

Updated to v. 1.2: added a new option to switch the images manually (navigation).

Updated to v. 1.3.2: added prevnext (previous / next links) option. In following bugfix releases fixed few bugs related to using prevnext and links options simultaneously. All generated elements moved into the element plugin is called from (as children and not as siblings any more).
At the moment the new version can be downloaded from GitHub, a new post with further details and update of the demo will be available a little bit later.

31 thoughts on “jQuery Unobtrusive Background Image Switcher

  1. Hi, this is lovely thank you.

    One thing though the div wouldn’t show as a background, so I changed :
    #bg-body {
    position: relative;
    }
    to
    #bg-body {
    position: absolute;
    }
    Works perfect with WordPress 3.5.1

  2. Is there any possibility to remove automatic slideshow and place next and previous button for slide show in this bg image switcher.
    Hoping for help asap, urgent please.

    • Hi there! We had many heavy images that had to be used as the fullscreen background with minimum impact on load times – that’s the reason this plugin was developed.

      This means the first loop takes each image after each timeout, loads it and then shows it. Should we have any kind of array based interactive navigation we’d have to preload all the images at once or make user wait after clicking prev/next/whatever while the requested image loads.

      So no, there is no built in possibility to do that. One way to extend the plugin with this kind of functionality without killing the purpose by preloading all the images is to extend the “updateImage” method by dynamically adding some kind of thumbs or markers that would link to already loaded images.

      If the whole lightweight full screen bg switching thing is not your goal though you might want to use another less specialized image slider, there are plenty that can do the trick out of the box.

      Yuriy

    • Hi Vas,

      thanks for the feedback. The slider wouldn’t start if you give it just one image, no further actions needed, it will just work as an image preloader.

      Should you require it not to loop while having more than one image – should be easy to add such an option (loop: true) to “defaults” and check it in init().

      If you mean you want to stop the slider while it runs – there is no such option at the time. I think it would require some tweaking of updateImage() method as well as some testing making the plugin a little less lightweight ๐Ÿ™‚

      Yuriy

  3. Pingback: Antivirus Software Blog » jQuery Unobtrusive Background Image Switcher 1.2.0

  4. Pingback: ใƒฌใ‚นใƒใƒณใ‚ทใƒ–ใชใƒ•ใƒซใ‚นใ‚ฏใƒชใƒผใƒณ็”ปๅƒ๏ผˆๅˆ‡ใ‚Šๆ›ฟใˆๅŠนๆžœไป˜ใ๏ผ‰ใ‚’่ƒŒๆ™ฏใซใ€ŒUnobtrusive Background Image Switcherใ€ - jQueryใƒ—ใƒฉใ‚ฐใ‚คใƒณใพใจใ‚ใฎใ‚ซใƒซใƒž

  5. Hi, its very easy to use, so i like it ๐Ÿ˜‰
    Now it works out of the box that the image is always centered, no regards the resolution. Now when i have a resolution of 1024×768 it no longer centers. it looks like the img stop sliding to the left, (outside the viewport so to say).

    any thoughts?

    • Hi Dennis,

      that is how “Perfect Full Page Background Image” solution from CSS tricks works.

      You can center the images with some extra work if you call the plugin from body like that:

      $(‘body’).bcatBGSwitcher({
      urls: srcBgArray
      });

      and use following CSS rules:

      body img {
      /* Set rules to fill background /
      min-height: 100%;
      min-width: 1024px;
      / Set up proportional scaling /
      width: 100%;
      height: auto;
      / Set up positioning /
      position: fixed;
      top: 0;
      left: 0;
      }
      @media screen and (max-width: 1024px) { / Specific to this particular image /
      body img {
      left: 50%;
      margin-left: -512px; / 50% */
      }
      }

      where 1024px is your images width, if you have other width change these numbers, also 512px is half of the image’s width. It will work everywhere but IE8, will not be centered there. If you need to support this feature there, take a look at respond.js

      Hope it helps!

      Regards,
      Yuriy & Vladimir

  6. Hi there,

    This is a very good plugin. It is nice and simple. Is there any parameters can be used to pause and replay the underlying slideshow when it runs?

  7. Hi ๐Ÿ™‚

    Great plugin! Good job ๐Ÿ™‚
    Just a thought… is it possible to point to a directory where the images are stored, therefore not needing to change the array in the script every time I need to change the images?

    • Hi Johny,

      thanks for the feedback. Your question has rather to do with server side programming and therefore not the job of anything JS / jQuery.

      Iโ€™d recommend generating the array with your system of choice so that a directory doesnโ€™t have to be created each time you need a new set of images.

      Though if you have PHP available, you can do something like this to get all images in a directory and throw em into an array:

      var srcBgArray = [< ?php
      $fileList = array();
      $files = scandir('/path/to/images/');
      foreach((array)$files as $file){
      if (!getimagesize ($file) ) continue;
      $fileList[]=$file;
      }
      echo โ€œโ€˜โ€.implode(โ€œโ€˜,โ€™โ€, $fileList).โ€โ€˜โ€;
      ?>];
      

      or get all .jpg files:

      var srcBgArray = [< ?php
      $fileList = array();
      foreach (glob("/path/to/images/*.jpg") as $filename) {
      $fileList[]=$filename;
      }
      echo โ€œโ€˜โ€.implode(โ€œโ€˜,โ€™โ€, $fileList).โ€โ€˜โ€;
      ?>];
      

      both peaces of code are not tested, but I hope you get the idea.

      Regards from Germany,
      Yuriy

  8. Hello! I would just love to use this code! I am just having trouble figuring it out. Am I suppose to have some code that in java script and have it link to the designated page? I viewed the source of the example you provided and it links to somewhere in the header. Do I include that to, because once I click on the link it’s directs me to more code. So sorry for bombarding you with questions! I would appreciate an explanation from you guys!

    • hey there,

      no rocket science here – since it’s a jQuery plugin you’ll have to load jQuery – in header

      <script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>

      and the plugin itself – in header

      <script type="text/javascript" src="js/jquery.bcat.bgswitcher.min.js"></script>

      then you can initiate it on your page. You would do pretty much the same with any jQuery Plugin out there

  9. Hey! I’m using this slider and im trying to figure out how to solve a small issue. When the slider is running in the background for a while (minimized or out of focus tab) and you bring back the focus to the slider all the images start switching super fast as if trying to catch up for all the time it was out of focus.

    Is there any way to solve this? Somehow make the slider to stop when out of focus?

    • Hi Ignacio, that sounds like a weird bug, I use it on a number of projects and never noticed such thing nor have it reported, so it should be something project-specific like a conflict with another script or plugin.

      Can you reproduce the issue on our demo ( http://www.bcat.eu/data/demo/jquery-bg-switcher/fullscreen/ )? I’ve just let it be inactive for few minutes and never got any catch-ups ๐Ÿ™‚ Should you stuck, send me a link I’ll see if there’s any problem there.

      Yuriy

      • Well, you were absolutely right! I was using another js script in the page (foundation) and as soon as i removed that the problem went away.

        Thx for the reply and great work on the script!

        • Still a little weird that foundation script somehow tampered JS setInterval function (can’t see any other explanation), their code used to be pretty good.
          Anyway glad you solved it and thanks for the feedback, nice to hear.

          Yuriy

  10. I have an issue using the script on chrome as it doubles the images I used and the id aswell…I am using the fixed type. Hope to get an answer from you. Thanks and more power

  11. Pingback: ่ƒŒๆ™ฏ็”ปๅƒใ‚’ๅˆ‡ใ‚Šๆ›ฟใˆใ‚‹ jQuery BgSwitcher ใฎใƒ—ใƒๆ”น้€  | Design Hack and Slash

  12. Pingback: Download Source Code jQuery Unobtrusive Background Image Switcher 2.0.0 | emka.web.id

  13. Pingback: jQuery Unobtrusive Background Image Switcher - Pixel Library

  14. Hello! This is a perfect script, and I would love to use it!
    I’m trying to implement it, however, and all that I get is the blank grey background, no images. Is there something I’m missing?

    • Hey, yeah that doesn’t sound right ๐Ÿ™‚ Maybe fetch the demo and go from there or open console and see what’s wrong.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.