HEX to RGB Converter

by prompt-07

Level: beginner • Mithril.js Version: latest

This example shows a simple converter, that converts any Hex color code to its RGB value. You can enter e hex color and the appropriate RGB value is shown and the HTML body takes the color you entered.

Live Example

Dependencies

Type Name URL
scriptmithril@latesthttps://unpkg.com/mithril@latest

JavaScript

var root = document.getElementById('wrap');
var userInput = '';
var r = '';
var g = '';
var b = '';
var store = '';
m.mount(root, {
	view: ()=> m(fetchColor, {colorCode: '#4682b4'})
});

function checkForRGB(userInput){
  if(userInput.length == 3){
  	userInput =
      userInput[0]
      +userInput[0]
      +userInput[1]
      +userInput[1]
      +userInput[2]
      +userInput[2];
  }

  r = parseInt(userInput.slice(0,2), 16);
  g = parseInt(userInput.slice(2,4), 16);
  b = parseInt(userInput.slice(4,6), 16);

  if( !(isNaN(r) || isNaN(g) || isNaN(b))){

  	document.body.style.backgroundColor = '#'+userInput;
  	let str = "rgb("+r+","+g+","+b+")";
  	document.getElementById('rgb').innerText = str;
  }


}


function fetchColor({attrs}) {

	const oninput = (e) => {
		userInput = e.target.value;
		if(userInput.length == 3 || userInput.length == 6)
			checkForRGB(userInput);

	}

	const onkeydown = (e) =>{
		if(e.keyCode == 13){

			if(userInput.length == 3 || userInput.length == 6)
				checkForRGB(userInput);

		}
	}

	function view(){

		return m('div.wrap',
			[m('input.hex[placeholder=#hexacode]', {
				oninput,
				onkeydown,
				value: userInput
			}),
			 m('lable#rgb')]
		)
	}


	return {view}
}

HTML

<div id='wrap'></div>

The snippet requires the latest version of Mithril.js framework. It is ideal for beginners showing some basic recipes.

In this example we can see an example of Mithril.js' m.mount API method, besides it core m() hyperscript function.

The code sample was authored by prompt-07. It was last modified on 24 October 2021.

Contribute

Do you see some improvements, that could be addressed here? Then let me know by opening an issue. As an alternative, you can fork the repository on GitHub, push your commits and send a pull request. To start your work, click on the edit link below. Thank you for contributing to this repo.

See more code examples  •  Edit this example on GitHub