jQuery: writing plugins in ECMAScript strict mode

by gabrieleromanato

HTML

<div id="test"></div>

CSS

#test {
    margin: 1em;
    border: thick solid;
    background: green;
    width: 200px;
    height: 200px;
}

.piece {
    float: left;
}

JavaScript

(function($) {
    
    'use strict';

    $.fn.colorize = function(options) {

        var self = this;
        var settings = {
            color: '#ccc',
            delay: 100,
            pieces: 10
        };

        options = $.extend(settings, options);

        var splitElement = function(element) {

            var width = element.width();
            var height = element.height();
            var pieceWidth = (width / options.pieces) + 'px';
            var pieceHeight = (height / options.pieces) + 'px';
            var totalPieces = options.pieces * options.pieces;

            for (var i = 0; i < totalPieces; i++) {

                $('<span class="piece"/>').
                css({
                    height: pieceHeight,
                    width: pieceWidth,
                    backgroundColor: options.color
                }).appendTo(element).hide();

            }

        };

        return self.each(function() {

            var $element = $(self);
            splitElement($element);

            $element.on('click', function() {

                var $delay = 0;

                $('span.piece', $element).each(function() {

                    var $piece = $(this);

                    $piece.queue('fade', function(next) {

                        $piece.delay($delay).fadeIn(300, next);

                    });

                    $piece.dequeue('fade');

                    $delay += options.delay;

                });


            });


        });

    };

})(jQuery);

$('#test').colorize({
    color: '#000',
    delay: 15
});