Changing Images Shockingly Fast with JavaScript

This is a dead simple solution to the following problem, “Develop a JavaScript-based solution for changing background images very fast”.

  1. There are one or more sets of images, each with the same number of images.
  2. Perform the following loop
    1. After a configurable random amount of time
    2. randomly choose an image set
    3. preload all images from set and
    4. show images in order using a very short delay between each frame.
    5. Display a standard image and start loop again.

See GitHub repository, it was once made for the German music band “Monster unter meinem Bett”, but they don’t use it any more.

How to use it:

  1. Create a directory imageshock/imagesets image sets
    1. each directory has a number as its name (N, to support random numbers for choosing an image set) and
    2. contains a fixed set of images, each named N_M.ext, e.g. 1_1.jpg for the first image in the first image set, 1_5.jpg for the fifth image in the first image set
  2. In your HTML page
    1. Create a <div id="imageshock-preload"> to preload images
    2. Optionally create a <span id="imageshock-counter"> for a counter showing the number of seconds left until the next ‘shocking event’
    3. Load scripts and execute jQuery plugin when page is loaded.

For example:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="css/style.css">
    </head>
    <body>
        <div>
            <span id="imageshock-counter" style="font-size: 48px; color: black;"></span>
        </div>
        <div id="imageshock-preload">
        </div>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>
        <script type="text/javascript" src="js/jquery.imageshock.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#imageshock-preload').imageshock();
            });
        </script>
    </body>
</html>

You can set some options when using imageshock:

    var defaultOptions = {
        imageSets: 'imageshock/imagesets',
        fileextension: 'jpg',
        startImage: 'imageshock/index.jpg',
        counterSelector: '#imageshock-counter',
    };

Set them like this:

    $(document).ready(function() {
        $('#imageshock-preload').imageshock({
            fileextension: '.png'
        });
    });

Have fun.

This entry was posted in Software Development and tagged . Bookmark the permalink.