Changing the background image of a div using JavaScript is done simply by using the getElementById method along with the backgroundImage property.
document.getElementById("div1").style.backgroundImage = "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 backgroundImage property in the following JavaScript code:
document.getElementById("div1").style.backgroundImage = "url('anotherImg.jpg')";
We can also do this in jQuery using the css() method.
Changing the Background Image of a Div in JavaScript with a Click
To change the background image of a div using JavaScript, we can target the backgroundImage property 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.
We can utilize both the backgroundImage property of #div1 along with an onclick event to change the background image.
We will also add some code so that the user can switch between both images as many times as they want.
Below is the JavaScript code which will allow the user to be able to update the background image of the div:
function changeImage(){
//Here we are just checking which image is showing, and displaying the other
if( document.getElementById("div1").style.backgroundImage.indexOf('1') > -1 ) {
document.getElementById("div1").style.backgroundImage = "url('https://daztech.com/wp-content/uploads/example-img2.png')";
} else {
document.getElementById("div1").style.backgroundImage = "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 JavaScript is below:
Code Output:
Full Code:
Hopefully this article has been useful for you to understand changing the background image in JavaScript.