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 *

Explore More

How to Center a Popup Window on Screen

JavaScript window.open() method is used to open a popup window. This popup window will be placed in the center of the screen. This example creates the pop-up window without placing it into

How to hide URL in the popup window opened using window.open

If you are using below code to open a popup window in your web page, then address must be appearing in you pop up window and f you want to

window.showModalDialog is deprecated in Edge and Chrome

If you have a website being compatible with Edge/Chrome and in past it was only compatible with IE 11 and if you are using window.showModalDailog in your JavaScript code, then