Open In App

How to get a div’s background image with jQuery ?

The task is to get a div’s background image with jQuery. You can achieve this task by using the CSS() method in jQuery. 

In simple words, we need to create an empty div and on click event, the empty div will get the image as a background.



CSS(): This is an inbuilt method in jQuery to add the CSS property but in this case, we need to provide complete property using the URL() method.

Syntax:



URL(): This is a CSS function that is used to include a file. It accepts a single parameter URL in string format.

Syntax:

url(" <string> <url-modifier> ")

Example 1: First, create an empty div with a button. Map that button to CSS() method in jQuery. Use an image to place in the div element after the button was clicked.




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      .box {
        width: 600px;
        height: 500px;
        border: 6px solid green;
      }
    </style>
    <script src=
    <script>
      $(document).ready(function () {
        $("button").click(function () {
          var imageUrl = "gfg.jpg";
          $(".box").css("background-image", "url(" + imageUrl + ")");
        });
      });
    </script>
  </head>
  <body>
    <div class="box"></div>
  
    <p><button type="button">
         click here to see the background img.
       </button>
    </p>
  </body>
</html>

Output:

Example 2:




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <style>
      .box {
        width: 600px;
        height: 500px;
        border: 6px solid rgb(61, 65, 61);
      }
    </style>
    <script src=
    </script>
    <script>
      $(document).ready(function () {
        $("button").click(function () {
          var imageUrl = "g.jpg";
          $(".box").css("background-image", "url(" + imageUrl + ")");
        });
      });
    </script>
  </head>
  <body>
    <div class="box"></div>
  
    <p><button type="button">click here !!</button></p>
  
    <style>
      button {
        background-color: blueviolet;
        align-items: center;
        margin-left: 250px;
      }
    </style>
  </body>
</html>

Output:


Article Tags :