A quick jQuery function to add some snazzyness to any page, image or header. Admittedly a little pointless though!

This could definitely be expanded further, I’d quite like to get some methods in here to be able to change the speed and also pause the effect altogether. I did write it with that in mind so should be easy to complete.

pixelate

Download Sourcepixelate.zip - 2kb

HTML

<div id="sandbox">
    <h1>pixelate</h1>
</div>

CSS

#sandbox{
    width:100%;
    height:400px;
    background:#00B060 url(http://lorempixel.com/1100/400/nature/3/) center no-repeat;
    overflow:hidden;
}

#sandbox h1{
    position:relative;
    height:400px;
    line-height:400px;
    font-size:3em;
    color:#FFF;
    z-index:100;
    text-align:center;
    text-shadow:2px 2px 4px #000;
}

jQuery Function

$.fn.pixelate = function (options) {
    var randOpacity = function (min, max) {
        return (min + (Math.random() * (max - min))).toFixed(2);
    };

    $(this).each(function () {
        var self = this,
            settings = {
                cellSize: 10,
                threads: 4,
                speed: 200,
                minOpacity: 0,
                maxOpacity: 1
            },
            threads = [],
            opts = $.extend({}, settings, options),
            cols = Math.ceil($(self).width() / opts.cellSize),
            rows = Math.ceil($(self).height() / opts.cellSize),
            r = 0,
            c = 0,
            t = 0,
            s = 0;

        for (r = 0; r < rows; r += 1) {
            for (c = 0; c < cols; c += 1) {
                $(self).append(
                    $('<div/>')
                        .addClass('cell_' + r + '_' + c)
                        .width(opts.cellSize)
                        .height(opts.cellSize)
                        .css('background', '#000')
                        .css('opacity', randOpacity(opts.minOpacity, opts.maxOpacity))
                        .css('position', 'absolute')
                        .css('left', c * opts.cellSize)
                        .css('top', r * opts.cellSize)
                );
            }
        }

        var changeRandomCell = function () {
            setTimeout(function () {
                var col = Math.round(Math.random() * cols),
                    row = Math.round(Math.random() * rows);
                $('.cell_' + row + '_' + col, self).css({'opacity': randOpacity(opts.minOpacity, opts.maxOpacity)});
                changeRandomCell();
            }, opts.speed);
        };
        for (t = 0; t < opts.threads; t += 1) {
            changeRandomCell();
        }

    });

    return this;
};

JavaScript

$(function () {
    $('#sandbox').pixelate({cellSize: 40, threads: 4, speed: 50, minOpacity: 0, maxOpacity: 0.7});
});