Last Updated: February 25, 2016
·
724
· restlessdesign

Random Lightning

Need to add some lightning to your page for Halloween? Use the following class to get started. Feel free to add methods for starting & stopping or setting the options through an object parameter!

/**
 * @class Lightning
 * @author Kevin Sweeney <kevin@vimeo.com>
 * @license http://www.apache.org/licenses/LICENSE-2.0
 *
 * @constructor
 * @param {Element} el The element to apply the 
 *     lightning effect to (defaults to body).
 */
function Lightning(el) {
    var source_el = el || document.body,
          source_style = source_el.style,
          source_bg_color = '#000',
          flash_bg_color = '#ddd',
          flash_delay = 60, // milliseconds
          min_delay = 5, // seconds
          max_delay = 12, // seconds
          min_flashes = 2,
          max_flashes = 3,
          flash_count = -1;

    function randomDelay() {
        var delay = 1000 * (min_delay + (Math.floor(Math.random() * (max_delay - min_delay + 1))));
        return delay;
    }

    function flashOn() {
        source_style.backgroundColor = flash_bg_color;
    }

    function flashOff() {
        source_style.backgroundColor = source_bg_color;

        if (--flash_count > 0) {
            setTimeout(flash, flash_delay);
        }
        else {
            setTimeout(lightningStrike, randomDelay());
        }
    }

    function flash() {
        flashOn();
        setTimeout(flashOff, flash_delay);
    }

    function lightningStrike() {
        flash_count = min_flashes + Math.floor(Math.random() * (max_flashes - min_flashes + 1));
        flash();
    }

    setTimeout(lightningStrike, randomDelay());
}

Then call it like so:

var lightning_storm = new Lightning();​

2 Responses
Add your response

Would love to see a demo, do you have a link you could include?

over 1 year ago ·

@mdeiters I slapped it in JSFiddle to play with: http://jsfiddle.net/XFzET/1/

It's quite cool!

over 1 year ago ·