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:
Recommended Posts:
- HTML | DOM Style backgroundImage Property
- jQuery | jQuery.fx.interval Property with example
- jQuery | jQuery.support Property
- jQuery | jquery Property
- jQuery | jQuery.fx.off Property
- jQuery | length property
- jQuery | context Property
- jQuery | event.which property with Examples
- jQuery | event.data Property
- jQuery | event.target Property with Example
- jQuery | event.relatedTarget Property with Example
- jQuery | event.delegateTarget Property
- jQuery | event.namespace Property
- jQuery | event.timeStamp property with Example
- jQuery | event.currentTarget Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



