Rotate color hue when iterating through a loop using Stylus

739 views Asked by At

How can I spin the color hue for each item in a loop?

If I have:

items = {
   item1: 'item1',
   item2: 'item2',
   item3: 'item3'
}

For each item in this list, I want to change it's hue by 30%.

Something like this:

for name, item in items
  .{name}
     color: hue(green, 30%)
1

There are 1 answers

2
SzybkiSasza On BEST ANSWER

If you aim at using CSS only, no-javascript solution, I would recommend using LessHat or similar framework (details about hue rotation for LessHat could be found here: https://github.com/madebysource/lesshat/blob/master/mixins/hue-rotate/hue-rotate.md). You can statically generate list of rotated items, however it will only work for given (and constant) list of items.

Using Stylus you could try:

items = {
   'item1': {
    'color': red
    'index': '1'
   }
   'item2': {
    'color': green
    'index': '2'
   }
   'item3': {  
    'color': blue
    'index': '3'
   }
}

for key, value in items
  .{key}
    color: hue(value[color], 30% * value[index])

If you want to dynamically change hue of given elements, you have to use Javascript - I would recommend using JQuery Color library (found here: https://github.com/jquery/jquery-color/).

IMPORTANT NOTE: Example below is using angle changes (hue is descibed as angle between 0 and 360, if it would be described by percentage, red would not be affected, because its value is 0 deg).

Example could be found here: http://jsfiddle.net/5r5w4x7g/4/

var changeHue = function(angle) {
    // Check if angle is between 0 and 360   
    if (angle) {
        if(angle>= 0 && angle<= 360) {
            classes.forEach(function(cls) {  
                // Get element with class
                var element = $('.'+cls);
                if(element.length) {                    
                    // Get current color and build JQuery Color object
                    var currentColorStr = element.css('background-color');
                    var color = $.Color(currentColorStr);
                    var hue = color.hue();                    
                    // Change hue by percentage and round it
                    hue = +hue + (+angle);
                    color = color.hue(hue);                    
                    // Set new color
                    element.css('background-color', color);
                }
            });
        }
    }
}