Open In App

How to Create a Photo Slideshow with fadeIn and fadeOut using jQuery ?

Last Updated : 02 Jul, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to create a simple slideshow with jQuery fadeIn() and fadeOut() functions. 

Approach:

  • For the slideshow effect for all the images, we are going to use the JavaScript setInterval() function. This function calls a function or evaluates an expression at specified intervals which is given in milliseconds.
  • fadeIn(): This method gradually increases the opacity of selected elements i.e. it changes from hidden to visible. 
  • fadeOut(): This method is used to fadeOut a specific element. 

Example: In the below code, we are creating an HTML <div> element with the first image of our slideshow. Next, we are adding CSS to style our slideshow. Then, we load jQuery library into our script.

We are using an array to store all the images of our slideshow. We are using the setInterval() function with fadeIn() and fadeOut(). We are using the attr() method to change the image source.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
  
    <style>
        .slideshow {
            margin: auto;
            width: 60%;
            border: 3px solid #73ad21;
            padding: 10px;
        }
  
        .slideshow img {
            width: 100%;
            height: 100%;
        }
    </style>
      
    <script>
        $(document).ready(function () {
            var pic = $("img:first");
            var images = [
            ];
  
            var i = 0;
            setInterval(function () {
  
                // Returns 0, 1, 2, 3, 0, 1, 2, ....
                i = (i + 1) % images.length;
                pic.fadeOut(250, function () {
                    $(this).attr("src", images[i]);
                    $(this).fadeIn(1050);
                });
            }, 5000);
        });
    </script>
</head>
  
<body>
    <div class="slideshow">
        <img src=
    </div>
</body>
  
</html>


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads