Build a Bulk HEX to RGBA Color Converter in Browser Using Vanilla Javascript Full Project For Beginners

 

 

Welcome folks today in this blog post we will be building a bulk HEX to RGBA color converter in vanilla javascript. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

<textarea name="colours" id="colours" cols="30" rows="10">
#004177
#00489A
#005DAA
#000000
#FFFFFF
#ed3124
#008a00
#FAFAFA
#D3D5D7</textarea>
<button id="go">Hex to RGBA</button>

 

 

script.js

 

 

// Actual conversion basically stolen from http://www.javascripter.net/faq/hextorgb.htm
const Red = (hex) => parseInt(cutHex(hex).substring(0,2),16);
const Green = (hex) => parseInt(cutHex(hex).substring(2,4),16);
const Blue = (hex) => parseInt(cutHex(hex).substring(4,6),16);
const cutHex = (hex) => (hex[0]==="#") ? hex.substring(1,7):hex;

const hexToRGBA = colour => "rgba(" + Red(colour) + ',' + Green(colour) + ',' + Blue(colour) + ",1)";

const bulkConvert = (colours) => colours
  .split("\n")
  .map(hexToRGBA)
  .join("\n");

const convertColours = () => {
  const textArea = document.getElementById('colours');
  const convertedColours = bulkConvert(textArea.value);
  textArea.value = convertedColours;
} 

const button = document.getElementById('go');

button.addEventListener('click', convertColours);

Leave a Reply