In this blog post, we learn how to change background images using javascript. Here we use the Style backgroundImage Property. BackgroundImage property sets or returns the background image of an element.
Html
First, create a div area where we change the background image.
<a href="javascript:;" onclick="changeBackgroundImage()">Change backgroud image</a>
<div class="div_area" id="a">
</div>
CSS
Now create some CSS to set background image and div style properties.
.div_area
{
background-image: url("https://t4.ftcdn.net/jpg/03/02/74/89/360_F_302748918_Vs76DTDodjhhkYuCEFahu0LcoDZkBuaW.jpg");
background-size: cover;
border-radius: 5px;
height: 500px;
width: 1080px;
display:inline-block;
}
Javascript
Create a function changeBackgroundImage() to change Background Image Using Javascript
<script type="text/javascript">
function changeBackgroundImage(){
var el= document.getElementById('a').style.backgroundImage="url(https://image.shutterstock.com/image-photo/word-demo-appearing-behind-torn-260nw-1782295403.jpg)";
}
</script>
full code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change Background Image Using Javascript</title>
</head>
<body>
<a href="javascript:;" onclick="changeBackgroundImage()">Change backgroud image</a> <hr>
<div class="div_area" id="a">
</div>
<script type="text/javascript">
function changeBackgroundImage(){
var el= document.getElementById('a').style.backgroundImage="url(https://image.shutterstock.com/image-photo/word-demo-appearing-behind-torn-260nw-1782295403.jpg)";
}
</script>
<style>
.div_area
{
background-image: url("https://t4.ftcdn.net/jpg/03/02/74/89/360_F_302748918_Vs76DTDodjhhkYuCEFahu0LcoDZkBuaW.jpg");
background-size: cover;
border-radius: 5px;
height: 500px;
width: 1080px;
display:inline-block;
}
</style>
</body>
</html>

Brijpal Sharma is a web developer with a passion for writing tech tutorials. Learn JavaScript and other web development technology.