To change the background image using jQuery, you can use the jQuery CSS() method. For this, the whole property value is specified using the url() functional notation.
Approach: Suppose we have an image URL stored in a variable and then use css() method to change the value of background image.
Below example illustrates the above approach:
Example:
<!DOCTYPE html> < html lang = "en" >
< head >
< title >
jQuery Changing background-image CSS Property
</ title >
< style >
.box {
width: 700px;
height: 220px;
border: 2px solid black;
background-repeat: no-repeat;
background-image: url(
}
h1{
color:green;
}
</ style >
< script >
$(document).ready(function() {
// Change background image of a div by clicking on the button
$("button").click(function() {
var imageUrl =
$(".box").css("background-image", "url(" + imageUrl + ")");
});
});
</ script >
</ head >
< body >
< center >
< h1 >GeeksforGeeks</ h1 >
< h3 >
jQuery Changing background-image CSS Property
</ h3 >
< div class = "box" ></ div >
< p >
< button type = "button" >
Change Background Image
</ button >
</ p >
</ center >
</ body >
</ html >
|
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.