Rainbow text HTML element

in code


Eadaoin asked for this, as a dare. Not an ID identifier, not a class identifier, but a bona fide <rainbow-text> custom HTML5 element. And here we are, all pretensions of worthiness in this project cast to the wind. I used the rainbow colour chart on Wikipedia for the array.

'use strict';

var rainy = 'rainbow-text';

// A-l-l-l-l-l the colours of the rainbow.
var rainbowColours = [
    '#FF0000',
    '#FF7F00',
    '#FFFF00',
    '#00FF00',
    '#0000FF',
    '#4B0082',
    '#8B00FF',
];

$(function() {
    var rainbowElement = document.registerElement(rainy, {
        prototype: Object.create(HTMLElement.prototype)
    });

    $(rainy).each(function() {
        var str = $(this).text();
        var newStr = '';

        for (var i = 0; i < str.length; i++) {
            newStr += '<span style="color: ' + rainbowColours[(i >= rainbowColours.length) ? i % rainbowColours.length : i]  + ';">' + str[i] + '</span>';
        }

        $(this).html(newStr);
    });
});

Except for the element this is no different than any other way to wrap text in rainbow colours.

<rainbow-text>HOLY SHIT RAINBOW TEXT</rainbow-text>

becomes

<rainbow-text>
    <span style="color: #FF0000;">H</span>
    <span style="color: #FF7F00;">O</span>
    <span style="color: #FFFF00;">L</span>
    <span style="color: #00FF00;">Y</span>
    <span style="color: #0000FF;"> </span>
    <span style="color: #4B0082;">S</span>
    <span style="color: #8B00FF;">H</span>
    <span style="color: #FF0000;">I</span>
    <span style="color: #FF7F00;">T</span>
    <span style="color: #FFFF00;"> </span>
    <span style="color: #00FF00;">R</span>
    <span style="color: #0000FF;">A</span>
    <span style="color: #4B0082;">I</span>
    <span style="color: #8B00FF;">N</span>
    <span style="color: #FF0000;">B</span>
    <span style="color: #FF7F00;">O</span>
    <span style="color: #FFFF00;">W</span>
    <span style="color: #00FF00;"> </span>
    <span style="color: #0000FF;">T</span>
    <span style="color: #4B0082;">E</span>
    <span style="color: #8B00FF;">X</span>
    <span style="color: #FF0000;">T</span>
</rainbow-text>


Decompression

in me


Your email address will not be published. Required fields are marked *