How to change the background color by using HEX code in input

Hello.

I need to change the color of an element when entering the HEX code in an input field.
I saw this post (Change the background of the input field based on user input), but I need it for any color / code, not for specific color list.
Thank you for your support!

Change Color.zip (42.5 KB)

03

very basic:

hex.addEventListener("change", myFunction);

function myFunction(e) {
let hexColor = (e.target.value).trim();

if(hexColor.indexOf('#') != -1) textToChange.style.setProperty('color', hexColor)
}

but would any user know the hexcolors?

4 Likes

Thank you @h_classen Hans! :pray:

There is a scenario in my project where the user might have this need.

Since I was working on it.

You can use css variables.

<style>
	:root {
  --hexcolor: #E8EBED;
  --smallsampleFont: darkgrey;
  
}


.sceneBackground{
background-color: var(--hexcolor)!important;
}
</style>

and

	var hexInput = document.getElementById("hex")
 	var rootEl = document.querySelector(':root');

	
	hexInput.onchange = function(event){
  		 
	 	rootEl.style.setProperty('--hexcolor', event.target.value);
 }

Change Color.hype.zip (64.0 KB)

4 Likes

Thank you so much @MarkHunte!
Thank you for your effort and I wish you all the best! :pray:

This version shows you the advantage of using the vars.

Since we are using a class name with the background, we just have to give that class to other elements. i.e other scene backgrounds.

They will pick up automatically the same colour.

This one also shows you your font change using the same idea and the additional HTML attributes for the font option buttons.

	<style>
	:root {
  --hexcolor: #E8EBED;
  --wishTextFont: Inter;
}


.sceneBackground{
background-color: var(--hexcolor)!important;
}

.wishText{
font-family: var(--wishTextFont)!important;
}
</style>

and

var wishText_ = document.getElementById("wishText")
var rootEl = document.querySelector(':root');
rootEl.style.setProperty('--wishTextFont', element.dataset.font);

Update:
I forgot to add the wish text class name 'wishText' to both text boxes on each scene

Change Color and Font.hype 2.zip (126.3 KB)

3 Likes

Waa, thank yooou @MarkHunte ! :pray: :partying_face:

1 Like

Note also since we are not forcing only hex colours, you can also use named colours.

i.e , red, pink, purple and so on, which gets around people not know hex colours.. (@h_classen very good point )

2 Likes

Amazing detail! I was not aware about it!
Thank you!

1 Like