Friday, September 23, 2011

JQuery - Image Slide Show using JQuery

In this article i will show you how to create dynamic Image slide show using JQuery and Web Service.

Step 1
Download JQuery Script from the following Link
JQuery 1.6.4

Step 2
Create a Web Application and give the solution name as SolSimpleSlideShowJQuery.


Step 3
Save images in Folder,Create a New Folder in the Solution and give folder name as Images,it is look like this


Click on Image for better View


Step 4
Add XML file in the App_Data folder and give the file name as ImageData.xml,it is look like this


Click on Image for better View


Step 5
The XML in the following example defines an XML document with a root node called Images. This root node contains one or more nodes called Image that include elements called ImagePath,it's look like this
<?xml version="1.0" encoding="utf-8" ?>

<Images>

  <Image>
    <ImagePath>Images/1.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/2.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/3.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/4.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/5.jpg</ImagePath>
  </Image>
 
  
</Images>

Step 6
Create ImageEntity Class in App_Code Folder,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class ImageEntity
{
    #region Property

    public String ImagePath
    {
        get;
        set;
    }

    #endregion
}

Step 7
Add a Web service in the web application solution and give the name as WebServiceSlideShow.asmx,it's look like this




Click on Image for better View


Step 8
Now create a web method in web service for retrieving data from XML document.it is look like this 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;

/// 
/// Summary description for WebServiceSlideShow
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class WebServiceSlideShow : System.Web.Services.WebService {

    public WebServiceSlideShow () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public List<ImageEntity> GetImagesData()
    {
        try
        {
            // Load Xml Document  
            XDocument XDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/ImageData.xml"));

            // Query for retriving all Images data from XML  
            var Query = from Q in XDoc.Descendants("Image")
                        select new ImageEntity
                        {
                            ImagePath = Q.Element("ImagePath").Value
                        };

            // return images data  
            return Query.ToList<ImageEntity>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }
}

Note -  Uncomment the ScriptService attribute on the class to allow for JSON style results.


Now Code-behind part done.Let see the design and script part.


Step 9
First Drag and drop Image control on Div Tag,it is look like this
<div align="center">
        <asp:Image ID="ImgSlideShow" runat="server"/>      
</div>

Step 10
Create a CSS for Div Tag and Image Control inside the Head Tag,it is look like this
 

Step 11
Apply CSS on Div Tag and Image Control,it is look like this
<body>
    <form id="form1" runat="server">
    <div class="DivStyle" align="center">
        <asp:Image ID="ImgSlideShow" runat="server" CssClass="ImageStyle"   />      
    </div>
    </form>
</body>


Step 12
Add jQuery file Reference inside the head tag of the page,it is look like this
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript" language="javascript"></script>

Step 13
Add a below script inside the head tag.it is look like this
<script language="javascript" type="text/javascript">

        $(document).ready(function () {

            $.ajax(
                {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebServiceSlideShow.asmx/GetImagesData", // Specify the Webservice Name with Function name
                    data: "{}",
                    dataType: "json",
                    success: function (Data) {

                        // Get Images Data from Web Service
                        var ImagesData = Data.d;

                        // Get Length of Images
                        var ImagesLength = ImagesData.length; 

                        // Set First Loading Image to the Image Control
                        var ImageSlide = $("#ImgSlideShow"); // Pass ImageControl ID
                        ImageSlide.attr('src', 'images/Loading.gif');

                        // Set Interval of Images (Image Change in Every 3 Seconds)
                        setInterval(Slider, 3000); 

                        // Set Effect & Increment Images
                        function Slider() {

                            ImageSlide.fadeOut("slow", function () {

                                    $(this).attr('src', ImagesData[(ImagesData.length++) % ImagesLength].ImagePath).fadeIn("slow");
                                        
                            });

                        }

                    },
                    error: function (E) {
                        alert(e.message);
                    }

                }
            )
        }
        ); 

    </script>

It makes use of the $.ajax(options) function within jQuery, and accepts an object with a number of optional properties. 
type specifies the HTTP method, which in this case is POST. 
url specifies the URL of the Web Service, together with the web method that is being called. This is followed by the parameters, which are applied to the data property. In this case, no parameters are being passed, as we are calling the method that retrieves the entire collection of Images Path from XML Document. 
The contentType and dataType MUST be specified. 
Following this are two further functions: success defines what should be done if the call is successful, and error handles exceptions that are returned.


We then use the JavaScript setInterval() function which delays execution of the Slider function for a specific time, in our case 3000 millisecond(3 seconds). The advantage of a setInterval() function is that it continues to repeat the process of triggering the function at a specified interval, thereby sliding the images in a cycle.


Run the Project.


Output


Click on Image for better View

Full .Aspx Code

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Simple Image Slide Show Using JQuery</title>

    <style type="text/css">
    
        <%-- CSS for Div Tag--%>
        .DivStyle
        {
            background-color:transparent;
            width:820px; 
            margin-left:auto;
            margin-right:auto;
            padding:10px;
            border:solid 5px #c6cfe1;
            }
            
           <%-- CSS for Image Control--%>
            .ImageStyle
            {
                 margin-left:auto;
                 margin-right:auto;
                 padding:10px;
                 border:solid 1px #c6cfe1;
                 height:500px;
                width:800px;
                }
    
    </style> 

    <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript" language="javascript"></script>  

    <script language="javascript" type="text/javascript">

        $(document).ready(function () {

            $.ajax(
                {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebServiceSlideShow.asmx/GetImagesData", // Specify the Webservice Name with Function name
                    data: "{}",
                    dataType: "json",
                    success: function (Data) {

                        // Get Images Data from Web Service
                        var ImagesData = Data.d;

                        // Get Length of Images
                        var ImagesLength = ImagesData.length; 

                        // Set First Loading Image to the Image Control
                        var ImageSlide = $("#ImgSlideShow"); // Pass ImageControl ID
                        ImageSlide.attr('src', 'images/Loading.gif');

                        // Set Interval of Images (Image Change in Every 3 Seconds)
                        setInterval(Slider, 3000); 

                        // Set Effect & Increment Images
                        function Slider() {

                            ImageSlide.fadeOut("slow", function () {

                                    $(this).attr('src', ImagesData[(ImagesData.length++) % ImagesLength].ImagePath).fadeIn("slow");
                                        
                            });

                        }

                    },
                    error: function (E) {
                        alert(e.message);
                    }

                }
            )
        }
        ); 

    </script>  

</head>
<body>
    <form id="form1" runat="server">
    <div class="DivStyle" align="center">
        <asp:Image ID="ImgSlideShow" runat="server" CssClass="ImageStyle"   />      
    </div>
    </form>
</body>
</html>

Download
Download Source Code

2 comments:

  1. Thank you very much for this great example.
    this was the only site that clearly showed how to create dynamic image slide show working with XML through Jquery that worked for me.
    I enjoyed your simple, straightforward example.

    Once Again Thanks......

    ReplyDelete