How to change background color using jQuery


When you need to change the background color of an element using jQuery, you can use the css() method of jQuery to set the background-color CSS property of the element.

For example, suppose you have an HTML <body> tag as follows:

<body style="background-color: yellow;">
  <h1>jQuery change background color</h1>
</body>

You can change the <body> background color by first selecting the element using jQuery selector $() and chain it with the css() method as follows:

$("body").css("background-color","blue");

The code above will change the background color from yellow to blue. You can also trigger the color change when a <button> element is clicked by using the .click() event handler method from jQuery.

Here’s an example code for that:

<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body style="background-color: yellow;">
  <h1>jQuery change background color</h1>
  <button id="btn">Change background</button>
  <script>
    $("#btn").click(function(){
      $("body").css("background-color","blue");
    })
  </script>
</body>

The click() method will execute the function you passed into it when the selected element is clicked.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.