Change Background Color of Div With jQuery toggleClass | Code Snippet #15

Change-Div-Background-With-jQueryCode Snippet #15: jQuery code snippet to change background color of div with jQuery toggleclass function. A simple code to toggle background color with the help of jQuery.

jQuery is a powerful framework to create anything and do anything. Today, we thought of sharing the code to change the background of a div element using jQuery’s toggleClass function.

Here, we are going to demonstrate how to change the background color of div with jQuery by clicking on the target div block.
Checkout the demo right below: (Test it by clicking on the div block)

HTML, CSS and jQuery used to change the background with jQuery:

HTML Markup:(Very Simple)


jQuery Code Snippet:


Initially, we create a small target box or target div with a color using CSS.

We add a CSS class which has the new color. We name this new CSS class as “changeBackground“. When the target box is clicked, the jQuery initiates the new class and adds that to the div as:

Hence, we initiate the new class with the help of the toggleClass function. The new CSS is applied to the div. The same code can be used to change the background properties using the click on the div. Even images can be used to replace the div. This is a very simple tutorial. Hope you enjoyed and found it helpful. If you have any clarifications, please let us know by commenting below.


Vinod Suthersan is a enthusiastic web designer still learning new things on web designing. He loves designing, hunting new designs, blogging, and crazy about Internet. Know more

You may also like...