Add li in to first place of ul with jQuery Ajax

by nolovelust 29. April 2010 15:15

Here is the simple JavaScript code to alter DOM with jQuery and add Ajax request result to the first place in a ul.

First add latest JQuery  reference to your page and create Ajax response page. In my case it is live.ashx which outputs data like below

<li>li1</li>

<li>li 2</li>

Than create an ul in your page like below

<ul id="LiveTraffic"></ul>

Then add below JavaScript and you are good to go 

 

var lastdata = null;
    var liCount = 0;
    $(document).ready(function () {
        $.get('live.ashx?' + Math.random(), function (data) {

            if (lastdata != data) {
                $("#LiveTraffic").prepend(data).slideDown('slow');
                lastdata = data;
                liCount += 1;
               }
        })

        if (liCount > 10) {
            $('#LiveTraffic li:not(:first)').remove();
            liCount = 0;
        }
        setTimeout(arguments.callee, 10000);
    });

Tags: , , ,

Useful

Tag cloud

Month List