Changing the background image using jQuery is done simply by using the jQuery css() method and the background-image property.
$("#div1").css("background-image", "url('someImage.jpg')");
Let’s say we have the following HTML with the following style:
To change the background image of #div1 from img.jpg to anotherImg.jpg, we will use the background-image property along with the css() method in the following jQuery code:
$("#div1").css("background-image", "url('anotherImg.jpg')");
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").css("background-image", "url('anotherImg.jpg')");
We can also do this in pure Javascript using the backgroundImage property.
Changing the Background Image of a Div in jQuery with a Click
To change the background image of a div using jQuery, we can combine the css() method with a click event.
Let’s say we have the following HTML and we want to change the background image of #div1 from example-img1.png to example-img2.png. Both images are the same image of gears, but with different colors.
Change background image
We can utilize both the jQuery click() method and jQuery css() method to change background image.
We will add some code so that the user can switch between both images as many times as they want.
Here is the jQuery code for changing a background image:
$("#click-me").click(function(){
//Here we are just checking which image is showing, and displaying the other
if( $("#div1").css("background-image").indexOf('1') > -1 ) {
$("#div1").css("background-image", "url('https://daztech.com/wp-content/uploads/example-img2.png')");
} else {
$("#div1").css("background-image", "url('https://daztech.com/wp-content/uploads/example-img1.png')");
}
});
The final code and output for this example of how to change the background image of a div using the jQuery css() method and JavaScript is below:
Code Output:
Full Code:
Change background image
Hopefully this article has been useful for you to understand changing the background image in jQuery.