This article will show you how to set the background image using jQuery. To set the background image, we are using the jQuery css() method.
jQuery css() Method
This method sets/returns one or more style properties for the specified elements.
Syntax:
-
Return a CSS property:
$(selector).css("propertyname");
-
Set a CSS property:
$(selector).css("propertyname", "value");
Example 1: In this example, background image is set by the background-image property using jQuery .css() method..
html
<!DOCTYPE html> < html >
< head >
< title >
Setting background-image
using JQuery CSS property
</ title >
< script src =
</ script >
< style >
body {
text-align: center;
}
#div {
width: 400px;
height: 250px;
}
</ style >
</ head >
< body >
< div id = "div" >
< h1 >GeeksforGeeks</ h1 >
< p >This is text of div box</ p >
< br >
< button >Click Here</ button >
</ div >
< script >
$('button').on('click', function () {
$('#div').css('background-image',
'url(' +
+ ')'
);
});
</ script >
</ body >
</ html >
|
Output:
Example 2: In this example, background image and background-repeat properties are set by the background property using JQuery css() method.
html
<!DOCTYPE html> < html >
< head >
< title >
Setting background-image using
jQuery css() Method
</ title >
< script src =
</ script >
< style >
body {
text-align: center;
}
#div {
width: 500px;
height: 350px;
}
</ style >
</ head >
< body >
< div id = "div" >
< h1 >GeeksforGeeks</ h1 >
< p >This is text of div box</ p >
< br >
< button >Click Here</ button >
</ div >
< script >
$('button').on('click', function() {
$('#div').css('background', 'url(' +
);
});
</ script >
</ body >
</ html >
|
Output: