JQuery | Setting background-image using CSS property
To set the background-image using CSS property, We’re using .css() method of jQuery. To understand example first understand the method.
JQuery .css() method:
This method set/return 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’s .css() method.
<!DOCTYPE html> < html > < head > < title > JQuery | Setting background-image using CSS property. </ title > < style > #div { background-repeat: no-repeat; margin-left: 120px; } </ style > < script src = </ script > </ head > < body style = "text-align: center;" > < div id = "div" > < h1 style = "color: green;" > GeeksForGeeks </ h1 > < p > This is text of the div box, . </ p > < br > < button > click to set </ button > </ div > < br > < br > < script > $('button').on('click', function() { $('#div') .css('background-image', 'url(' + + ')' ); $('h1').css('color', 'black'); }); </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button:
Example-2: In this example, background image and background-repeat properties are set by the background property using JQuery’s .css() method.
<!DOCTYPE html> < html > < head > < title > JQuery | Setting background-image using CSS property. </ title > < style > #div { margin-left: 120px; } </ style > < script src = </ script > </ head > < body style = "text-align: center;" > < div id = "div" > < h1 style = "color: green;" > GeeksForGeeks </ h1 > < p > This is text of the div box, . </ p > < br > < button > click to set </ button > </ div > < br > < br > < script > $('button').on('click', function() { $('#div') .css('background', 'url(' + content / uploads / 20190515121004 / gfgbg1.png '+ ' ) no - repeat ' ); $('h1').css('color', 'black'); }); </ script > </ body > </ html > |
Output:
- Before clicking on the button:
- After clicking on the button: