skip to Main Content

I want to create multiple buttons ROYGBV. I want to use JS to attribute a function whereby when I click a button, the background colour changes. The one I have just seems too long.
Can some help with this?

function myFunctionRed(){document.body.style.backgroundColor="red";}
function myFunctionOrange(){document.body.style.backgroundColor="orange";}
function myFunctionYellow(){document.body.style.backgroundColor="yellow";}
function myFunctionGreen(){document.body.style.backgroundColor="limegreen";}
function myFunctionBlue(){document.body.style.backgroundColor="blue";}
function myFunctionIndigo(){document.body.style.backgroundColor="#4B0082";}
function myFunctionViolet(){document.body.style.backgroundColor="violet";}

4

Answers


  1. You could simplify it in order to use only one function that accepts a color argument like:

    function setBodyBgColor(color) { document.body.style.backgroundColor = color; }
    

    and use like:

    setBodyBgColor("red");
    // or
    setBodyBgColor("hsla(180, 80%, 80%, 0.8)")
    

    You could make it even more flexible, and also pass the element you want to style:

    function setBgColor (elem, color) { elem.style.background = color; }
    
    setBgColor(document.body, "blue");
    

    But, it makes not great use to have a function that all it does is change a background color. Instead, create a function that can apply any style, and more CSS properties at once:

    const css = (el, styles) => typeof styles === "object" ? Object.assign(el.style, styles) : el.style.cssText = styles;
    
    
    // Use like:
    
    css(document.body, {
      color: "red",
      background: "blue",
      fontSize: "2rem"
    });
    
    // Or like:
    
    css(document.querySelector("#someElement"), `
      color: red;
      background: blue;
      font-size: 2rem;
    `)
    
    Login or Signup to reply.
  2. function myColor(color,element) {
      let el = document.querySelector(element);
      element.style.backgroundColor = color;
    } 
    
    //use in html 
    <button onclick="myColor('red','body')">R</button>
    <button onclick="myColor('green','body')">G</button>
    
    Login or Signup to reply.
  3. Here is my suggestion

    It is longer than just passing a colour to a function but it shows you some interesting methods to study

    const colors = {
      "red": "red",
      "orange": "orange",
      "yellow": "yellow",
      "limegreen": "limegreen",
      "blue": "blue",
      "hex": "#4B0082",
      "violet": "violet"
    };
    const colorKeys = Object.keys(colors);
    const colorEntries = Object.entries(colors);
    
    const createStyleSheet = () => {
      let head = document.querySelector('head'),
        style = document.createElement('style'),
        css = colorEntries
        .map(([name, color]) => `.${name}-bc { background-color: ${color}}`)
        .join('n');
      css += '.colorButton { text-transform: capitalize;}'; // Uppercase first letter of button text
      style.type = 'text/css';
      style.appendChild(document.createTextNode(css))
      head.appendChild(style);
    };
    window.addEventListener('DOMContentLoaded', () => {
      createStyleSheet();
      const bodyCL = document.body.classList;
      const colorDiv = document.getElementById('colorDiv');
    
      colorDiv.innerHTML = colorEntries
        .map(([name, color]) => `<button class="colorButton ${name}-bc" value="${name}">${color}</button>`).join('');
      colorDiv.addEventListener('click', (e) => {
        const tgt = e.target;
        if (!tgt.matches('.colorButton')) return; // not a button
        colorKeys.forEach(color => bodyCL.remove(`${color}-bc`)); // remove previous
        bodyCL.add(`${tgt.value}-bc`);
      });
    })
    <div id="colorDiv"></div>
    Login or Signup to reply.
  4. You can simplify the function like below :

    function setBackgroundColor(color){
      document.body.style.backgroundColor = color;
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search