Convert Hex Color to RGB and HSL

Convert Hex Color to RGB and HSL
Code Snippet:HEX => RGB => HSL Converter
Author: Pankaj Parashar
Published: January 29, 2024
Last Updated: February 3, 2024
Downloads: 64
License: MIT
Edit Code online: CodeHim
Read More

Convert Hex Color to RGB and HSL is a handy code snippet designed for web developers. The code allows you to effortlessly convert hexadecimal color codes to their corresponding RGB and HSL values. By simply entering a hex code in the provided input field, the JavaScript function dynamically updates the RGB and HSL values in real-time. This tool streamlines the color conversion process, ensuring accuracy and convenience in managing color schemes for web design.

How to Convert Hex Color To RGB and HSL

1. First of all, load the Normalize CSS by adding the following CDN link into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

2. Create three HTML input elements with an ID of “hex”, “rgb”, and “hsl” to capture the hexadecimal color code and display converted output:

<input type="text" placeholder="hex" id="hex">
<input type="text" placeholder="rgb" id="rgb">
<input type="text" placeholder="hsl" id="hsl">

3. Customize the CSS styles as needed to match your project’s design. The following CSS styles are a starting point, but feel free to modify them.

body { margin: 5% auto; background: #fff; }

input {
  font-size: 44px;
  padding: 20px;
  font-family: courier;
  font-weight: bold;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  border-radius: 5px;
  border: 4px solid rgba(0,0,0,.15);
  display: block;
  margin: 50px auto;
  width: 80%;
  background: rgba(255,255,255,0.9);
  overflow: hidden;
  text-overflow: ellipsis;
}

input:focus {
  outline: 0;
  border: 4px solid rgba(0,0,0,.3);
  -webkit-box-shadow: 0 0 10px rgba(0,0,0,.3);
}

4. Now, load the jQuery by adding the following CDN link just before closing the body tag:

<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

5. Finally, initialize the color conversion functionality by adding the following script at the end of your HTML file or within a document-ready block:

$(window).load(function(){

	/* For quick copy-paste */
    $('input').focus(function(){this.select();});

	/* Change color on every key input. */
	$('#hex').bind('blur keydown', function (event) {
		var el = this;
		setTimeout(function () {
			var rgb = [],
			    $input = $(el),
			    fail = false,
			    original = $input.val(),
			
			hex = (original+'').replace(/#/, '');
			
			if (original.length === 1 && original !== '#') { $input.val('#' + original); }
			if (hex.length == 3) hex = hex + hex;

			for (var i = 0; i < 6; i+=2) {
			   rgb.push(parseInt(hex.substr(i,2),16));
			   fail = fail || rgb[rgb.length - 1].toString() === 'NaN';
			}

			$('#rgb').val(fail ? '' : 'rgb(' + rgb.join(',') + ')');
			$('#hsl').val(fail ? '' : 'hsl(' + rgbToHsl.apply(null, rgb).join(',') + ')');
			   
			$('.cd__main').css('backgroundColor', $('#rgb').val());
	    }, 13);
	});

    /* Function to convert rgb-to-hsl. */
	
	function rgbToHsl(r, g, b){
		r /= 255, g /= 255, b /= 255;
		var max = Math.max(r, g, b), min = Math.min(r, g, b);
		var h, s, l = (max + min) / 2;

		if (max == min) { h = s = 0; } 
		else {
			var d = max - min;
			s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

			switch (max){
				case r: h = (g - b) / d + (g < b ? 6 : 0); break;
				case g: h = (b - r) / d + 2; break;
				case b: h = (r - g) / d + 4; break;
			}
			
			h /= 6;
		}
		
		return [(h*100+0.5)|0, ((s*100+0.5)|0) + '%', ((l*100+0.5)|0) + '%'];
	}
});


$(document).ready(function() {
 
    if ( !("placeholder" in document.createElement("input")) ) {
        $("input[placeholder], textarea[placeholder]").each(function() {
            var val = $(this).attr("placeholder");
            if ( this.value == "" ) {
                this.value = val;
            }
            $(this).focus(function() {
                if ( this.value == val ) {
                    this.value = "";
                }
            }).blur(function() {
                if ( $.trim(this.value) == "" ) {
                    this.value = val;
                }
            })
        });
 
        // Clear default placeholder values on form submit
        $('form').submit(function() {
            $(this).find("input[placeholder], textarea[placeholder]").each(function() {
                if ( this.value == $(this).attr("placeholder") ) {
                    this.value = "";
                }
            });
        });
    }
});

That’s all! hopefully, you have successfully created a simple tool to convert Hex code to RGB and HSL values. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...