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:
- addchild and removeChild DOM methods for Edge and Chrome
- How to remove JavaScript Objects from memory
- On click of parent page pop up window should stay on top only
- Open a Fixed-Size Popup Without Minimize/Maximize Effects
- How to Center a Popup Window on Screen
- How to hide URL in the popup window opened using window.open
- window.showModalDialog is deprecated in Edge and Chrome
- Cloning JavaScript Object with Object.create
- Set new Attribute in XML using jQuery
- DOMParser: parseFromString() method
- What is the use of attr() method in jQuery?
- What is jQuery CDN?
- Difference between $(this) and ‘this’ in jQuery
- jQuery important questions
- Checkbox validation in jQuery
- Difference between offset and position in jQuery?
- How to change the background image using jQuery?
- jQuery Methods
- jQuery Selectors
- jQuery Downloading
- jQuery History
Comments are closed.