javascriptfunctioncolorsuser-inputtextcolor

How to change color of text based on user input in Javascript


I would like to change color of the header based on what color the user chooses and types in in the input box provided.

I just can't figure out how to type correctly

if (user input === color){

document.getElementById("header").style.color ="that color"

in other words if user input equals a color type, change the header color to the color specified.

I'm not sure if adding ids to the list helps in any way, sorry this is one of my first exercises in JS

This is the HTML:

    <h1 id="header"> Hi There </h1>

    <p>Choose from one of the following options!</p>

<ul>
    <li id="darkred">Dark red</li>
    <li id = "darkorange">Dark orange</li>
    <li id = "yellow">Yellow</li>
    <li id = "darkgreen">Dark Green</li>
    <li id = "teal">Teal</li>
    <li id = "navy">Navy</li>
    <li id = "indigo">Indigo</li>
    <li id = "fuchsia">Fuchsia</li>
    <li id = "lavender">Lavender</li>
    <li id = "pink">Pink</li>
</ul>
<input type-"text" id="inp"/>

I mean i could write functions for every one of those colors and that would work, but that would be also be unnecessarily long and dumb and I'm trying to make more general functions here


Solution

  • You can create a button on click of which you will get the input color and then set it.

    But if you want to restrict the user to select only color from the list then you can get all colors and then match from it.

    const button = document.querySelector("button");
    const header = document.getElementById("header");
    
    const allColorsEl = document.querySelectorAll("ul > li");
    const allColors = [...allColorsEl].map(el => el.id);
    
    button.addEventListener("click", () => {
      const inputColor = document.querySelector("input").value;
      if (header && inputColor && allColors.find(color => color === inputColor)) {
        header.style.color = inputColor
      } else {
        console.log("Select color from list")
      }
    })
    <h1 id="header">Hi There</h1>
    
    <p>Choose from one of the following options!</p>
    
    <ul>
      <li id="darkred">Darkred</li>
      <li id="darkorange">Darkorange</li>
      <li id="yellow">Yellow</li>
      <li id="darkgreen">DarkGreen</li>
      <li id="teal">Teal</li>
      <li id="navy">Navy</li>
      <li id="indigo">Indigo</li>
      <li id="fuchsia">Fuchsia</li>
      <li id="lavender">Lavender</li>
      <li id="pink">Pink</li>
    </ul>
    <input type="text" id="inp" />
    <button>change color</button>