Home / Blog /
How to Change the Background Color with JavaScript
//

How to Change the Background Color with JavaScript

//
Tabnine Team /
2 minutes /
September 21, 2020

The background color is a Cascading Style Sheet (CSS) property of an element. We use CSS to modify this color, as well as for laying out the design of a webpage. Modifying this property changes the color displayed in the background of an element.

NOTE: The background of an element includes its padding and border, but not its margin. You will need to take this into account when developing your page design.

CSS properties are easily changed in code (to learn more about modifying CSS with JavaScript, check out this link). In this article we’ll walk through how to manipulate the background-color CSS property using JavaScript.

Two elements are required to perform the change:

  1. An event to trigger the change. This can be a DOM event, a JavaScript event (e.g. events generated using setTimeout()), or using CSS pseudo-classes.
  2. A function that is responsible for making the change (with the exception of using CSS pseudo-classes).

A basic example

Take the following sample JavaScript and HTML, which create a <p> element containing a background color when clicked.

JavaScript

function changeBgc(el) {
  el.style.backgroundColor = 'yellow';
}

HTML

<p onclick="changeBgc(this)">
  Click to change background color
</p>

In this code, the triggering event is onclick (defined as a property on the <p> element). When the click handler is called, the event will be routed to the changeBgc() method we describe above..

The changeBgc() function receives the this object as a parameter. The this object contains the HTML element itself. We can access the styles for this element with the .style property, which gives us access to the .backgroundColor CSS property. The code uses this property to assign the value “yellow” to the element, changing its background color to yellow.

Note: Using the style property will add inline styling to the element. Inline CSS is the most specific level of CSS that can be applied to an object, applying to an individual element itself. It thus overrides most other CSS declarations for an element.

This approach centers on using element properties in JavaScript to modify the inline style for an element. There are two other ways that JavaScript can use to change a CSS property:

  1. Setting the style attribute for the element directly by using the setAttribute() method.
  2. Adding or removing a class from an element using the classList property and its associated methods (i.e. the add() method, among others).

 

Related Articles:

JavaScript – How to Use setAttribute

JavaScript – How to Change CSS

JavaScript – How to Set an HTML Element’s Class Using JavaScript