Skip to content

Instantly share code, notes, and snippets.

@rnagle
Created June 25, 2015 15:20
Show Gist options
  • Save rnagle/24b6a1325f33da56549b to your computer and use it in GitHub Desktop.
Save rnagle/24b6a1325f33da56549b to your computer and use it in GitHub Desktop.

Revisions

  1. rnagle created this gist Jun 25, 2015.
    58 changes: 58 additions & 0 deletions rainbows.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,58 @@
    var rainbows = rainbows || {};

    (function() {
    var $ = jQuery;

    rainbows.last_offset = 0;

    rainbows.colors = [
    'red', 'green', 'yellow', 'blue', 'orange',
    'purple', 'pink', 'brown', 'black', 'gray', 'white'
    ];

    rainbows.wrap = function(target) {
    var target = $(target),
    new_target = $('<div>'),
    nodes = target.contents().clone();

    nodes.each(function() {
    if (this.nodeType == 3) { // text
    var new_html = "";
    text = this.wholeText;

    for (var i=0; i < text.length; i++) {
    if (text[i] == ' ')
    new_html += " ";
    else
    new_html += "<span>" + text[i] + "</span>";
    }
    new_target.append(new_html);
    } else {
    $(this).html(rainbows.wrap(this));
    new_target.append(this);
    }
    });

    return new_target.html();
    };

    rainbows.colorize = function(target, offset) {
    var colors = $.extend([], rainbows.colors);

    if (typeof offset !== 'undefined')
    colors = colors.concat(colors.splice(0, offset));

    $(target).find('span').each(function(idx, el) {
    $(el).attr('class', colors[(idx % colors.length)]);
    });
    };

    rainbows.start = function(target, interval) {
    $(target).html(rainbows.wrap(target));
    rainbows.intervalId = setInterval(function() {
    rainbows.colorize(target, rainbows.last_offset);
    rainbows.last_offset = (rainbows.last_offset + 1) % rainbows.colors.length;
    }, interval || 500);
    };

    }());