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:

Comments are closed.

Explore More

addchild and removeChild DOM methods for Edge and Chrome

Below we are creating a JavaScript utility that fully supports the functionality of the DOM (like appendChild, removeChild, etc.) in Microsoft Edge and other modern browsers involves wrapping standard DOM

On click of parent page pop up window should stay on top only

To ensure the popup window stays on top of the parent page, you can use the window.open() method with specific focus-handling logic. JavaScript allows you to bring the popup window

How to remove JavaScript Objects from memory

To remove unused objects and improve memory management in JavaScript, you generally rely on the JavaScript engine’s garbage collection mechanism. However, you can aid this process by explicitly removing references