Monday, August 5, 2013

Changing the order of Listview randomly on page refresh

Changing the order of Listview randomly on page refresh
In this article i would like to share how to Change the order of Listview items randomly on page refresh using Jquerymobile and javascript.I have already shared based on jquery mobile and Javascrpt.


First,Add this script files in Head Tag
 






Next,Add the Basic html code to display the listview items

Page Title


Page Footer

Now, Use the following script to bind items in listview.

$('#Itemslistpage').live('pageshow', function (event) {
    var serviceURL = 'Service.asmx/GetList';

    $.ajax({
        type: "POST",
        url: serviceURL,
        data: param = "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {

        // parse it as object
        var ItemsListArray = JSON.parse(data.d);
        var ArrayRank = new Array();
        // creating html string
        var listString = '
    '; var k = 0; // running a loop $.each(ItemsListArray, function (index, value) { ArrayRank[k] = k; k++; }); random(ArrayRank); $.each(ItemsListArray, function (index, value) { listString += '
  • ' + ItemsListArray[ArrayRank[index]].Desgination + '
    ' + ItemsListArray[ArrayRank[index]].Name + '' + ItemsListArray[ArrayRank[index]].Rank + '
  • '; }); listString += '
'; //appending to the div $('#ItemsLists').html(listString); // refreshing the list to apply styles $('#ItemsLists ul').listview(); } function errorFunc() { alert('error'); } });
Now coming to Main Logic, that is changing the order of listview randomly using the following script
function random(list) {
    
            var i, j, t;
            for (i = 1; i < list.length; i++) {
                j = Math.floor(Math.random() * (1 + i)); 
                if (j != i) {
                    t = list[i];
                    list[i] = list[j];
                    list[j] = t;
                }
            }
        } 

That's it.Now The listview items order will change on every time page refresh.See the below output Here is the output

Labels: , , ,