Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an item to the top of a dynamic list

Like the title states, does anyone out there have a clear way to implement this type of functionality?

Example: If you go to http://weewar.com, in their front page you noticed an ajax module that updates every second. However, all of the new items are added to the top of the list. My question is around that very same functionality.

Does anyone have an easy and clear idea as to how one would implement this functionality?

So far I have a method that initially creates the list, then another method is called in an interval that pulls the most recent data from the server..

However, I'm stuck with, how can I add the new dynamic node to the top of the list.

If you can guide me to where I can find this information or give me an idea as to how I can implement this I will be very happy and grateful.

like image 733
ericg Avatar asked Jan 21 '23 22:01

ericg


2 Answers

jQuery would make it pretty easy for you. Here's an example:

jQuery

$(document).ready(function(){
  $('<div>News 1</div>').prependTo('#textbox');
  $('<div>News 2</div>').prependTo('#textbox');
  $('<div>News 3</div>').prependTo('#textbox');
  $('<div>News 4</div>').prependTo('#textbox');
});

HTML

<div id="textbox"></div>

Output

News 4
News 3
News 2
News 1

As you can see, the news that was added first gets pushed downwards.

like image 101
Gert Grenander Avatar answered Feb 01 '23 08:02

Gert Grenander


If you use jQuery you can use jQuery('#list_ID:first-child').prepend(new_item);

If you want to do it the old fashion way, document.getElementById('list_ID').innerHTML = new_item + document.getElementById('list_ID').innerHTML;

Or you can use a more DOM friendly method:

var list_item = document.createElement('li'); list_item.innerHTML="Some Text" document.getElementById('list_ID').insertBefore(list_item, document.getElementById('list_ID').firstChild);

like image 35
Aaron Harun Avatar answered Feb 01 '23 08:02

Aaron Harun