Search code examples
javascriptcssrandomrgbhsl

Turning RGB values into HSL values in a random Javascript


I have a random color overlay on the media-boxes of this site.

http://www.reportageborsen.se/reportageborsen/wordpress/

I had some really good help from the mates here at stackoverflow wich resulted in this script:

var getRandomInRange = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};
$('.media-box').each(function() {
    var mediaBox = $(this);
    var mask = mediaBox.find('.mask');
    var hue = 'rgb(' + getRandomInRange(100, 255) + ',' + getRandomInRange(100, 255) + ',' + getRandomInRange(100, 255) + ')';
    mask.css({
            backgroundColor : hue,
        opacity : 0.7            
             });
    mediaBox.hover(function() {
        mask.stop(true, true).fadeIn();
    }, function() {
        mask.stop(true, true).fadeOut();
    });
});​

Fiddle link: http://jsfiddle.net/b5ZPq/3/

However, I would love to have more of the brighter colors and less of the greyish ones. I understand that it can be done with HSL values instead of RGB values.

So I tried to convert the css background rgb values to hsl values and also converted the script, but I didn't get it to work.

var getRandomInRange = function(min, max) {
    return Math.floor(Math.random() * (max - min + 1), 10) + min;
};
$('.media-box').each(function() {
    var mediaBox = $(this);
    var mask = mediaBox.find('.mask');
    var hue = 'hsl(' + getRandomInRange(0, 360) + ',' + getRandomInRange(70, 100) + '%' + getRandomInRange(45, 55) + '%)';
    mask.css({
        backgroundColor: hue,
        opacity: 0.7
    });
    mediaBox.hover(function() {
        mask.stop(true, true).fadeIn();
    }, function() {
        mask.stop(true, true).fadeOut();
    });
});​

http://jsfiddle.net/zolana/Kc9U4/5/ (the fiddle, updated, working: http://jsfiddle.net/zolana/Kc9U4/9/ )

(I'm not looking for a script that converts all the RGB values to HSL values (I know there are scripts with that purpose) rather to have a solid script for this specific task.)


Solution

  • Remember that when you use HSL colors (and others), you need to separate each value with a comma and use the correct notation. In this case, it looks like the following.

    hsl ( int hue , int saturation % , int lightness % )

    You were missing a comma after the second argument (specifically right after the percent sign).

    var hue = 'hsl(' + getRandomInRange(0, 360) + ',' + getRandomInRange(70, 100) + '%,' + getRandomInRange(45, 55) + '%)';
    

    http://jsfiddle.net/b5ZPq/4/