JavaScript - Convert RGB to Hex

In this tutorial we will create a Convert RGB to Hex using JavaScript. JavaScript is a scripting or programming language that allows you to implement complex things on web pages. It is widely used in designing a stunning website. It is an interpreted programming language that has a capabilities of Object-Oriented. This code can be used as your calculator to any mathematical problem. So Let's do the coding...

Getting started:

This is the link for the bootstrap that i used for the layout design https://getbootstrap.com/.

The Main Interface

This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.

JavaScript - Convert RGB to Hex


RGBA

HEX

Creating the Script

This code contains the script of the application. This code will convert the rbg into hex for better use in the layout. To do this just copy and write these block of codes as shown below inside the text editor and save it as script.js inside the js folder. function convert(){ var r = document.getElementById("r").value; var g = document.getElementById("g").value; var b = document.getElementById("b").value; var hex = document.getElementById("hex"); if(r == "" || g == "" || b == ""){ alert("Please enter something!"); }else{ if(r > 255 || g > 255 || b > 255){ alert("The given value is too large enough to convert!"); }else{ var rgb= "rgb("+r+", "+g+", "+b+")"; hex.value = rgb2hex(rgb); } } } function rgb2hex(rgb){ rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i); return (rgb && rgb.length === 4) ? "#" + ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : ''; } There you have it we successfully created a Convert RGB to Hex using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

Add new comment