Converting RGB color values to HSL color values using a unique, randomized Javascript approach

On this site, I have added a random color overlay to the media-boxes.

Check it out here

Thanks to the helpful folks at stackoverflow, I was able to create 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();
    });
});​

You can view the fiddle link here

I wanted more bright colors and less grey ones, so I attempted to switch from RGB values to HSL values in the CSS background.

The updated script looked like this:

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();
    });
});​

Updated working Fiddle: here

(I'm specifically looking for a script that focuses on this task rather than converting all RGB values to HSL)

Answer №1

Always remember to correctly format your HSL colors by separating each value with a comma and using the proper notation. Here is an example of how it should look:

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

In this particular case, you forgot to include a comma after the second argument (specifically right after the percentage sign).

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

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

Answer №2

Take a look at this code snippet I created:

function generateRandomColor(){
    var h = Math.random();
    var s = 0.99;
    var v = 0.99;

    h = h + 0.618033988749895;
    h = h % 1;

    var r, g, b;

    var i = Math.floor(h * 6);
    var f = h * 6 - i;
    var p = v * (1 - s);
    var q = v * (1 - f * s);
    var t = v * (1 - (1 - f) * s);

    switch(i % 6){
        case 0: r = v, g = t, b = p; break;
        case 1: r = q, g = v, b = p; break;
        case 2: r = p, g = v, b = t; break;
        case 3: r = p, g = q, b = v; break;
        case 4: r = t, g = p, b = v; break;
        case 5: r = v, g = p, b = q; break;
    }

    return "rgba("+Math.floor(r*255)+","+ Math.floor(g*255)+","+ Math.floor(b*255)+","+ 0.2+")";
}

This function creates a random Hue value along with constant values for brightness and saturation. As a result, it produces a bright and different RGB color each time due to the utilization of the golden ratio. Feel free to use this code and let me know if you encounter any issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Positioning a dropdown menu on top of a Google Map in React with JavaScript: Best Practices

I've been attempting to place a dropdown menu at a specific location on my Google Map, specifically in the top right (or top left is also acceptable). Below is the current output I am seeing: Here is the expected result: Modifications After trying ...

I am in need of eliminating repetitive comments from each post

data structure can you help figure out what is causing the issue in this code that seems to be removing old comments? mutations:{ getPosts(state) { let unique = [...new Set(state.posts)]; for (let i = 0; i < uniq ...

Even when there is a change in value within the beforeEach hook, the original value remains unchanged and is used for dynamic tests

My current project setup: I am currently conducting dynamic tests on cypress where I receive a list of names from environment variables. The number of tests I run depends on the number of names in this list. What I aim to achieve: My main goal is to manip ...

Tips on incorporating animations into a class design?

I'm trying to figure out how to make an image disappear by adding a class However, when I try this, the element vanishes without any animation I'd like it to fade away slowly instead I've heard there are CSS3 properties that can help achi ...

Creating an HTML Canvas effect where images are placed onto another image

Looking to create a similar effect as seen on this website () On this site, users can upload their images (4000 * 400) and have the option to add Mickey Mouse ears over their image before saving it. The Mickey Mouse ear is resizable from all four sides f ...

What is causing my HTML wrapper to malfunction?

Below is the HTML code for my website: <div id="wrapper"> <div id="header"> <img src="images/MyBannerFinished.jpg" alt="Header" width="803" class="headerimage" /> </div> <!--- End Header ---> <div id="navbar"> <ul ...

Unable to retrieve the value of a key from a node object

I'm baffled by how this is even possible For example, when I execute this code: console.error(order.Items[i]); The output is: { ItemURL: '', IsBundle: false, GiftTaxPrice: '0', GiftPrice: '0', GiftNotes: null ...

Bring in a video file in order to watch it on your web page (HTML)

Is there a way to upload and play a video file using the video element? I am looking to add a video file to my webpage that can be played using a video element. <input type="file"> <h3>Video to be imported:</h3> <video width="320" ...

container dimensions for images

Is there a way to make an image adjust its size according to the container? For example, if the container is 100x100 pixels and the image within it is 90x80 pixels, can we make sure that the smaller property of the image (height in this case) adjusts to f ...

Implementing two background images and dynamically adjusting their transparency

With the challenge of loading two fixed body background-images, both set to cover, I encountered a dilemma. The text on the page was extending below and scrolling, along with top and bottom navigation icons. As expected, the second background covered the f ...

When attempting to render a React child, it is important to note that objects are not valid (found: [object Promise]). If your intention was to display a collection of children, it is advised

Instructions in "/pages/blog/index.js" : import BlogComponents from "../../components/Blog/blogComponents"; import { listBlogs } from "../../server/mongodb"; const index = async (props) => { console.log(props) return ( ...

Vue event manager, accessible for all components

I have created a new Vue instance and assigned it to the window object, thinking that it would be accessible throughout all components. I expected this setup to allow me access to events emitted anywhere within my application. However, it seems like this ...

AJAX isn't quite cooperating - it seems that only the error callback is getting

Even though I have specified both success and error callbacks, the error callback is being triggered even when the status code is 200. In addition, I am also making a curl call to another php file within registry.php. This is what I have attempted: $.aj ...

Deactivate the EventListener to continue playing the video

I have a JavaScript function that pauses a video when it reaches 5 seconds. <video id="home-hero-video" preload autoplay="autoplay" muted="muted"> <source src="videourl.mp4" type="video/mp4& ...

Determining the exact position on a graph by calculating its value along the line of best fit

After analyzing the following dataset - | a | f | |-----------|---------| | £75.00 | 43,200 | | £500.00 | 36,700 | | £450.00 | 53,400 | | £450.00 | 25,700 | | £250.00 | 12,900 | | £1,600.00 | 136,000 | | £600.00 | 7 ...

Modifying background with JavaScript and AJAX技术

I currently have a table structured like the following; <table style="width: 100%; border: solid 1px #666600; min-width: 800px" cellpadding="0" cellspacing="0"> <tr> <td id="aaa">&nbsp;</td> ... Using jQuery's ajax functi ...

Arranging and structuring Handlebars templates

In this particular example... http://example.com/1 ...I am experimenting with organizing a Handlebars template and its corresponding content in separate files, as opposed to having them all combined in the HTML file or JavaScript script, like in this con ...

Preventing the mysql server called by php from running when the website is refreshed

My local website runs by querying a mysql database using inputs from an html form. The form values are passed to php via jQuery to execute the query. Is there a way to send a command to the mysql server to terminate the query if the web page is refreshed? ...

What is the method for fetching a WebElement with a specific CSS attribute using JavascriptExecutor?

Currently, I am faced with a situation in which I need to locate a WebElement based on its CSS property, specifically the background-color. I successfully crafted the JQuery script below to pinpoint the element using the firefox console: $('.search-b ...

The Gulp task is failing to generate the CSS file

Greetings! I have a task set up in my gulpfile.js as shown below: const gulp = require('gulp'); const sass = require('gulp-sass'); gulp.task('sass', function(){ return gulp.src('sass/*.scss') .pipe(sass()) ...