How to change the background image using jQuery?

Changing the background image using jQuery is very simple task now. You can change the background image using the css() method and url() function notation. The syntax to change the background image using jQuery is:

$("selector").css({"background-image": "url(image)"});  

We can directly pass the image to the url() function as given above, or it can be done by storing the image in a variable and pass the variable name to the url as given below.

var img = "image";  
$("selector").css({"background-image": "url(" + img + ")"});  

Example:

In this example, there is a div element with its background-image. We are using the css() method and url() function notation to change the background-image of the corresponding div element.

<html>  
<head>  
<style>  
#div1 {  
border: 3px solid red;  
background-image: url("first.jpg");  
height: 310px;  
width: 351px;  
}  
  
</style>  
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>  
  
<script>  
$(document).ready(function() {  
$("button").click(function() {  
$("#div1").css({"background-image": "url(new.png)"});  
});  
});  
</script>  
</head>  
  
<body>  
<center>  
<h4> This is an example of changing the background-image using jQuery. </h4>  
<div id = "div1"> </div>  
<p> Click the following button to change the background image of above div </p>  
<button>  
Change Image  
</button>  
</center>  
</body>  
  
</html>  

More on jQuery:

Leave a Reply

Your email address will not be published. Required fields are marked *