JavaScript/Changing element styles/Exercises

Topic: CSS style

We use the HTML page of the previous page for the exercises.



1. Modify the function toggle.

  • If the background color of 'div_1' is green, change it to aqua; else, change it back to green.
  • If the background color of the button is red, change it to yellow; else, change it back to red.
Click to see solution
function toggle() {
  "use strict";

  // locate div_1
  const div_1 = document.getElementById("div_1");
  if (div_1.style.backgroundColor !== "aqua") {
    div_1.style.backgroundColor = "aqua";
  } else {
    div_1.style.backgroundColor = "green";
  }

  // locate the button
  const button = document.getElementById("buttonToggle");
  if (button.style.backgroundColor !== "red") {
    button.style.backgroundColor = "red";
  } else {
    button.style.backgroundColor = "yellow";
  }
}



2. Be creative. Modify the function toggle so that other CSS properties change, e.g., div's text size, body's padding or background color, ... .



3. Modify the function toggle.

  • Ask the user prompt() which background color he prefers for the first div.
  • Change the background color of the first div to this color.
Click to see solution
function toggle() {
  "use strict";

  // locate div_1
  const div_1 = document.getElementById("div_1");
  
  // ask the user
  const tmp = prompt("What color do you prefer?");

  // change the color (if possible)
  div_1.style.backgroundColor = tmp;
}