Open In App

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

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

Approach:



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.






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


Article Tags :