how to insert new elements on page in reverse order using jQuery

prepend enries using jquery

I have been extending the current sample clock synchronization application to add some more features to show more capabilities of jQuery. In the last update I added functionality to display latency numbers when service was called every X number of minutes. If you will let the page running for quite some time you will see how quickly the entries get appended to the display. What we really want is that latest entries should be displayed at the top. So basically instead of appending the new entries, we want to prepend the new entry to the last entry added. We are in luck here. jQuery does offer couple of methods here that makes it easy. prepend, prependTo, before, insertBefore methods are your friend here. It turns out that all these methods get mapped to one function behind the scene, insertBefore. Following code snippet from the application shows entries are added in reverse order.

var elLastLatencyEntry;
var elLastMessageEntry;

function displayLatency() {
 var elToAppend = null;
 if (latency == -1) { elToAppend = $("<p>Initializing</p>"); }
 else { elToAppend = $("<p>" + latency + " ms</p>"); }
 if (null == elLastLatencyEntry)
 { elLastLatencyEntry = elToAppend.appendTo(elLatencyDisplay); }
 else { elLastLatencyEntry = elToAppend.prependTo(elLastLatencyEntry); }

You can see from the code that I save the last entry that was added in a variable for later use. This avoids over head of finding the latest entry again and again every X number of seconds.




8.6 °C / 47.4 °F

weather conditions Clouds

Monthly Posts

Blog Tags