How to Set background Image using jQuery css() Method ?
Last Updated :
11 Dec, 2023
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.
This method sets/returns one or more style properties for the specified elements.
Syntax:
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:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...