skip to Main Content

Is there a way for me to write less lines of codes for this function? I want it so that when you press either one of the buttons it will alternate between the two colors. function green() is the exact opposite of red.

<h1 id="header">Red Or Green</h1>
<button id="redButton" onclick="red()">Red</button>
<button id="greenButton" onclick="green()">Green</button>
function red() {
  document.getElementById("header").innerHTML = "Red"
  document.getElementById('header').style.color = "red"
  document.getElementById('redButton').style.color = "white"
  document.getElementById('redButton').style.backgroundColor = "red"
  document.getElementById('greenButton').style.color = "black"
  document.getElementById('greenButton').style.backgroundColor = "grey"
}

5

Answers


  1. // Cache the frequently accessed elements
    const headerElement = document.getElementById("header");
    const redButton = document.getElementById("redButton");
    const greenButton = document.getElementById("greenButton");
    
    // Event listener for the whole document, utilizing event delegation
    document.addEventListener("click", function(event) {
      const targetId = event.target.id;
      
      if (targetId === "redButton") {
        headerElement.innerHTML = "Red";
        headerElement.style.color = "red";
        redButton.classList.add("active-red");
        greenButton.classList.remove("active");
      } else if (targetId === "greenButton") {
        headerElement.innerHTML = "Green";
        headerElement.style.color = "green";
        greenButton.classList.add("active-green");
        redButton.classList.remove("active");
      }
    });
    .active {
      color: white;
    }
    
    .active-red {
      color: white;
      background-color: red;
    }
    
    .active-green {
      color: black;
      background-color: grey;
    }
    <h1 id="header">Red Or Green</h1>
    <button id="redButton">Red</button>
    <button id="greenButton">Green</button>
    Login or Signup to reply.
  2. You can try passing the color, based on which you can setting the styles like the following way:

    function toggleColor(color) {
        const header = document.getElementById('header');
        const redButton = document.getElementById('redButton');
        const greenButton = document.getElementById('greenButton');
        
        //set header text & color based on the color passed
        header.textContent = color === 'red' ? 'Red' : 'Green';
        header.style.color = color;
        
        //set red button's text & background color
        redButton.style.color = color === 'red' ? 'white' : 'black';
        redButton.style.backgroundColor = color === 'red' ? 'red' : 'grey';
        
        //set green button's text & background color
        greenButton.style.color = color === 'green' ? 'white' : 'black';
        greenButton.style.backgroundColor = color === 'green' ? 'green' : 'grey';
    }
    <h1 id="header">Red Or Green</h1>
    <button id="redButton" onclick="toggleColor('red')">Red</button>
    <button id="greenButton" onclick="toggleColor('green')">Green</button>
    Login or Signup to reply.
  3. You can create CSS classes instead and you can add and remove them based on your requirement.

    The following can be created:

    function red() {
      document.getElementById("header").innerHTML = "Red"
      document.getElementById('header').style.color = "red"
      document.getElementById('redButton').add("active-red");
      document.getElementById('greenButton').add("inactive");
    }
    
    function green() {
      document.getElementById("header").innerHTML = "Green"
      document.getElementById('header').style.color = "green"
      document.getElementById('redButton').add("inactive");
      document.getElementById('greenButton').add("active-green");
    }
    .inactive{
      color: black;
      background-color: grey;     
    }
    
    .active-red{
      color: white;
      background-color: red;   
    }
    
    .active-green{
      color: white;
      background-color: green;   
    }
    Login or Signup to reply.
  4. maybe something like this:
    with a <div id="buttons-group">

    const
      e_header  = document.querySelector('#header')
      e_buttons = document.querySelector('#buttons-group')
      ;
    e_buttons.onclick = e =>
      {
      if (!e.target.matches('button')) return;
      
      e_buttons.className = e_header.className = e.target.id; 
       
      e_header.textContent = e.target.textContent;
      }
    #buttons-group>button {
      color: black;
      background-color: grey;
      }
    #header.redButton   { color: red;   }
    #header.greenButton { color: green; }
    
    #buttons-group.redButton>#redButton {
      color            : red;
      background-color : white;
      }
    #buttons-group.greenButton>#greenButton {
      color            : green;
      background-color : white;
      }
    <h1 id="header">Red Or Green</h1>
    <div id="buttons-group">
      <button id="redButton"> Red   </button>
      <button id="greenButton"> Green </button>
    </div>
    Login or Signup to reply.
  5. For a DRY solution have one event handler that covers both button click events.

    1. You should remove your inline JS from the markup and use addEventListener.
    2. Use CSS classes, and add/remove/toggle them with classList.
    3. Add data attributes to your buttons to identify the colours. Use this value to swap between red and green.
    // Grab the elements, and add listeners to the buttons
    const header = document.querySelector('.header');
    const btns = document.querySelectorAll('button');
    btns.forEach(btn => btn.addEventListener('click', handleClick));
    
    // When a button is clicked...
    function handleClick(e) {
      
      // Grab the colour from its dataset
      const { color } = this.dataset;
      
      // Get its opposite colour
      const oppColor = color === 'red' ? 'green' : 'red';
      
      // Remove the header opposite colour
      header.classList.remove(oppColor);
      
      // Add the header clicked colour
      header.classList.add(color);
    
      // Set the text content of the header to the colour
      header.textContent = color;
    
      // Iterate over the buttons adding the selected
      // class if the current button is the button that
      // was clicked
      btns.forEach(btn => {
        btn.classList.toggle('selected', btn === e.target);
      });
      
    }
    .header { text-transform: capitalize; }
    .green { color: green; }
    .red { color: red; }
    button { color: black; background-color: gray; }
    [data-color="red"].selected { color: white; background-color: red; }
    [data-color="green"].selected { color: white; background-color: green; }
    <h1 class="header">Red Or Green</h1>
    <button type="button" data-color="red">Red</button>
    <button type="button" data-color="green">Green</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search