bhalash

Custom <x-rainbow> HTML element

Nov 25th, 2014
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. // The custom HTML element name.
  4. var rainy = 'x-rainbow';
  5.  
  6. // A-l-l-l-l-l the colours of the rainbow.
  7. var rainbowColours = [
  8.     '#FF0000',
  9.     '#FF7F00',
  10.     '#FFFF00',
  11.     '#00FF00',
  12.     '#0000FF',
  13.     '#4B0082',
  14.     '#8B00FF',
  15. ];
  16.  
  17. function centerText(element) {
  18.     // Vertically center the element's text.
  19.     $(element).css('padding-top', $(window).height() * 0.5 - $(this).height() * 0.5);
  20. }
  21.  
  22. $(function() {
  23.     centerText('h1');
  24.  
  25.     var rainbowElement = document.registerElement(rainy, {
  26.         // Declare the custom element.
  27.         prototype: Object.create(HTMLElement.prototype)
  28.     });
  29.  
  30.     $(rainy).each(function() {
  31.         // Grab the text of each x-rainbow element and wrap it in a span with the given colour.
  32.         var str = $(this).text();
  33.         var newStr = '';
  34.  
  35.         for (var i = 0; i < str.length; i++) {
  36.             newStr += '<span style="color: ' + rainbowColours[(i >= rainbowColours.length) ? i % rainbowColours.length : i]  + ';">' + str[i] + '</span>';
  37.         }
  38.  
  39.         $(this).html(newStr);
  40.     });
  41. });
  42.  
  43. $(window).resize(function() {
  44.     centerText('h1');
  45. });
Advertisement
Add Comment
Please, Sign In to add comment