Skip to content
Related Articles

Related Articles

Improve Article

How to smoothly transition CSS background images using jQuery?

  • Last Updated : 12 May, 2021

In this article, we will learn to implement a smooth transition of background images using jQuery and CSS.

Approach: 

  • First, we add a transparent background image using the background-image property in CSS in the style tag.
    background-image: url(white.jpg);
  • For the transition background image, we use the transition property in CSS and add a transition to the background image in the style tag.
    transition: background-image 3s;
  • In the script section, we create an image object and add the source of the image that needs to be transitioned. On image load, we call a function that adds background-image using the css() method in JQuery.

JavaScript Code snippet:

 var image = new Image();
// Image for transition
image.src = "geek.png";
image.onload = function () {
  $(".element").css("background-image", 
                    "url('" + image.src + "')");
};

Example:Below is the full implementation of the above approach.

HTML




<!DOCTYPE html>
<html>
  <head>
    <!-- JQuery CDN -->
    <script src=
    </script>
    <style>
      body {
        width: 100%;
        height: 100%;
      }
      .element {
        background-image: url(
        width: 60%;
        height: 100%;
        padding: 200px;
        background-repeat: no-repeat;
        transition: background-image 3s;
      }
    </style>
  </head>
  
  <body>
    <div class="element"></div>
  
    <script>
      var image = new Image();
  
      // Image for transition
      image.src =
      image.onload = function () {
        $(".element").css("background-image", 
                          "url('" + image.src + "')");
      };
    </script>
  </body>
</html>

Output:

Smooth transition




My Personal Notes arrow_drop_up
Recommended Articles
Page :