Open In App

How to Set background Image using jQuery css() Method ?

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:

 



Example 1: In this example, background image is set by the background-image property using jQuery .css() method..




<!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.




<!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:


Article Tags :