Skip to Content

How to change background color on every click in JavaScript?

Changing the background color of a web page or element is a common task in front-end web development. Using JavaScript, we can easily change the background color on click events by writing a simple script. In this post, we will go over a step-by-step guide on how to change the background color on every click using plain JavaScript.

Prerequisites

Before we get started, there are a few prerequisites skills you should have:

  • Basic knowledge of HTML and CSS
  • Familiarity with JavaScript syntax and concepts like variables, functions, DOM manipulation, etc.
  • Experience attaching click event listeners in JavaScript

As long as you understand the fundamentals of front-end web development, you should be able to follow along with this tutorial. We will be covering everything from scratch!

Step 1 – Create an HTML File

First, we need a basic HTML page to work with. Create an index.html file and add the following code:

<!DOCTYPE html>
<html>
<head>
  <title>Change BG Color on Click</title>
</head>
<body>

  <div id="container"></div>
  
  <script src="script.js"></script>
</body>
</html>

This sets up a basic page with an empty <div> element that we will use later. We also include our JavaScript file script.js which we will create next.

Step 2 – Generate Random Colors

In script.js, we will start by creating a function to generate random hex color values:

function randomColor() {
  let letters = '0123456789ABCDEF';
  let color = '#';

  for (let i = 0; i 

This function generates a string of 6 random hex digits, prefixing it with '#' to create a valid color value like #D891EF. We will use this to change the background to a random color on each click.

Step 3 - Select Container Element

Next, we need to select the <div> element that we want to change the background color of:

const container = document.querySelector('#container');

This uses document.querySelector to grab the element with the id of container.

Step 4 - Add Click Event Listener

Now we can add a click event listener to the container element:

container.addEventListener('click', function() {
  // Change background color
});

The callback function will run each time the container is clicked.

Step 5 - Change Background Color

Inside the click handler, we generate a random color and set it as the background color of the container:

container.addEventListener('click', function() {

  // Generate random color
  const bgColor = randomColor(); 
  
  // Set as background color
  container.style.backgroundColor = bgColor;

});

That's it! Now when you click on the <div>, it will change to a random background color.

Step 6 - Try it Out

Save your files and open index.html in a browser. Click on the <div> element a few times and see it change color on each click. Pretty simple!

Here is the full JavaScript code:

// Generate random color
function randomColor() {
  let letters = '0123456789ABCDEF';
  let color = '#';

  for (let i = 0; i 

Customizing the Script

With this basic script, there are many ways we can expand or customize the functionality:

  • Change background to random color on double click or mouse hover instead
  • Cycle through an array of preset colors instead of random
  • Change the text color to contrast with the background
  • Add transitions for a smooth color change
  • Allow the user to choose which element changes color
  • Save the changed color using localStorage

The possibilities are endless! Try expanding on the script and see what cool effects you can create.

Using Classes for Cleaner Code

As the script grows, we can encapsulate the logic into classes for cleaner code:

class ColorChanger {

  constructor(selector) {
    this.element = document.querySelector(selector);
    this.element.addEventListener('click', this.handleClick.bind(this));
  }

  handleClick() {
    const bgColor = this.generateColor();
    this.element.style.backgroundColor = bgColor;
  }

  generateColor() {
    // Function body...
  }

}

const changer = new ColorChanger('#container');

This allows us to reuse the color changer on multiple elements!

Using CSS Variables

Another option is to use CSS variables for changing the color:

:root {
  --bgColor: #fff;
}

#container {
  background-color: var(--bgColor); 
}

And in JS:

container.style.setProperty('--bgColor', randomColor());

This keeps the JS code clean and moves the color value into CSS.

Conclusion

Changing background color on click is a simple task with JavaScript event listeners. The key steps are:

  1. Generate random hex color values
  2. Select the element to change
  3. Add click event listener
  4. Set element's background color to random color

From here you can expand on the script to create all kinds of fun color changing interactions. Manipulating styles dynamically with JavaScript opens up many possibilities for unique interfaces. Give it a try on your own sites!

Summary

In this blog post, we walked through a step-by-step guide on how to change the background color of an element on click using JavaScript. Here are the key takeaways:

  • Use a simple loop to generate random hex color values
  • Select the target element with document.querySelector
  • Add a click event listener to the element
  • Inside the handler, set the element's background color to a random value
  • You can expand the script to cycle through presets, change text color, add transitions, and more
  • Use classes to encapsulate the color changer logic for reusability
  • Consider using CSS variables for cleaner separation from JavaScript

The full code example shows a simple implementation you can use to get started. Dynamic color changes can enhance UI interactions and make for interesting visual effects.

I hope you found this tutorial helpful! Let me know if you have any other questions.

Frequently Asked Questions

What is the easiest way to change background color in JavaScript?

The easiest way is to select the element and directly set the style.backgroundColor property to the desired color value:

const element = document.querySelector('#myElement'); 
element.style.backgroundColor = 'blue';

How do I cycle through multiple background colors on click?

You can create an array of possible colors and increment through them on each click. For example:

const colors = ['red', 'green', 'blue'];
let colorIndex = 0;

function changeColor() {
  element.style.backgroundColor = colors[colorIndex];
  colorIndex = (colorIndex + 1) % colors.length;  
}

Can this work for multiple elements on a page?

Absolutely! You can reuse the same color changer logic by selecting multiple elements and attaching the click handler to each one individually.

For example:

const elements = document.querySelectorAll('.my-elements');

elements.forEach(element => {
  element.addEventListener('click', changeColor); 
});

How do I save the changed color using localStorage?

When setting the new color, also update localStorage. On page load, initialize the color from localStorage:

// Set color
element.style.backgroundColor = newColor;
localStorage.setItem('bgColor', newColor);

// Get color
const savedColor = localStorage.getItem('bgColor'); 
element.style.backgroundColor = savedColor;

Example Code

Here is some example code for dynamically changing the background color of elements on click using JavaScript:

<!DOCTYPE html>
<html>
<head>
<style>
  .box {
    width: 100px;
    height: 100px;
    margin: 20px;
  }
</style>  
</head>
<body>

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

<script>
  const boxes = document.querySelectorAll('.box');

  function changeBg(event) {
    const bgColor = generateColor();
    event.target.style.backgroundColor = bgColor;
  }
  
  function generateColor() {
    // Function to generate random color
  }

  // Attach handler to all boxes
  boxes.forEach(box => {
    box.addEventListener('click', changeBg);
  });
</script>

</body>
</html>

This allows any number of elements to have their background color changed on click. The generateColor() function can return random colors, cycle through presets, or use any logic you need.

The click handler changes the specific target element that was clicked using event.target. This allows reuse of the same handler function for all boxes.

Conclusion

In summary:

  • Use JavaScript event listeners like click to detect user interaction
  • Dynamically generate or cycle through background color values
  • Set the background color style on the target element
  • The same logic can be reused for multiple elements
  • Local storage can save the changed color

Changing the background color is a great way to add visual interactivity to a page. Start with the fundamentals in this guide, then expand the functionality as needed for your specific project! Let me know if you have any other questions.