Search code examples
javascripthtmlcsscolors

Is there a way to make user select a color/colour with only the option that you give them in JavaScript/HTML?


Hey I was wondering if there is a way that you can make the user choose a colour/color with the options that you give them? I know there is a way to let user select a color/colour of thier choices but is there a way that you give the user only three options that change the background colour/color? for instance let say I want the user to only have the choice between black and blue how would I code this?

This is what I tried:

HTML Page:

<div class="colour selector">
    Pick a color <input onchange="colorSelected(this)" type="color">
  </div>

JavaScript Page:

function colorSelected (element) {
    document.body.style.background = element.value
}

But i want to be able to give the user limted options like only three colours (red, blue & yellow)


Solution

  • let select = document.getElementById("select");
    let text = document.getElementById("text");
    
    select.onclick = function() {
      switch (select.value){
          case "red":
            text.style.color = "red";
            select.style.backgroundColor = "red";
          break;
          case "pink":
            text.style.color = "pink";
          select.style.backgroundColor = "pink";
          break;
          case "blue":
            text.style.color = "blue";
          select.style.backgroundColor = "blue";
          break;
      }
    }
    .color1{
      background-color:red;
    }
    .color2{
      background-color:pink;
    }
    .color3{
      background-color:blue;
    }
    <select id="select">
      <option hidden selected value="">Choose a color</option>
      <option value="red" class="color color1"></option>
      <option value="pink" class="color color2"></option>
      <option value="blue" class="color color3"></option>
    </select>
    <p id="text">Some text</p>

    Edited version