How to smoothly transition CSS background images using jQuery?
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 = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" > </ script > < style > body { width: 100%; height: 100%; } .element { background-image: url( https://media.w3wiki.net/wp-content/uploads/20210507170406/white.jpg); 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 = "https://media.w3wiki.net/wp-content/uploads/20210507170600/gfg1-300x67.png"; image.onload = function () { $(".element").css("background-image", "url('" + image.src + "')"); }; </ script > </ body > </ html > |
Output:
Contact Us