<div id="block">Block</div>
#block {
  background-color: black;
  color: white;
  padding: 10px;
  cursor: pointer;
}
// "document" refers to the HTML web page representation in Javascript
// its method "getElementById" looks for an element
// with "id" equals to "block"
const block = document.getElementById('block');

// a variable that can be actually reassigned
// its data type is boolean: a value of true or false
let isDefaultColorApplied = true;

function toggleBlockColor () {
  if (isDefaultColorApplied) {
    block.style.backgroundColor = 'red';
    isDefaultColorApplied = false;
  } else {
    block.style.backgroundColor = 'black';
    isDefaultColorApplied = true;
  }
}

// "block" has a method "onclick" that will be called
// if we click on the block
// so we assign our custom callback function to tell our program
// how to behave
block.onclick = function () {
  // each time a click on the block occurs
  // we call "toggleBlockColor" function
  toggleBlockColor();
}
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.