Aniket Singh
Aniket Singh

Reputation: 877

Dynamically Load new Data into div and hide the old data

I have a Div where Latest News are fetch from database with php while loop shown up like->

Hello News 1

Hello news 2

Hello news 3

News are updated every 10000 milliseconds

Here is the HTML part php While Loop starts here

<div class="media">
<div class="media-object pull-left has-notif">
<i class="fa fa-flash"></i>
</div>
 <div class="media-body">
 <span class="media-heading"><?php echo $fot['message']; ?></span>
 <span class="media-meta time"><?php echo timeAgo($fot['time']); ?></span>
  </div>
  </div>

Loops end here. Here is What I've tried->

<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#news').load('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds

<div id="news"> </div>

Now the Problem I'm Facing is that it refreshes whole div, if new news is found than news number 3 should fade away & new news come at the top, if another news is found news 2 should fade away for e.g->

The ajax request found one news post so it will show up here

Hello News 2 // Hello news 1 should come above this news 2

Hello news 3

Hello news 4 //news 4 should fade away from the screen

Upvotes: 0

Views: 153

Answers (2)

H H
H H

Reputation: 2123

  1. Create a container to hold your news in:

    <div class="news_container"></div>

  2. Create a template for individual news items: It would be a good idea to use something like Mustache.js

    <div class="news_item"> <h1 class="news_title"></h1> <p class="news_content"></p> </div>

  3. Get record_count.php to send you back the news items in an array like this:

    $news = [ 'news_1_title' => 'Some news content here', 'news_2_title' => 'Some more content here', ];

  4. Loop through the array once you have them, clone the template and fill in the fields using the classes to find the part you want to fill in (or using the templating package you use), then .prepend() it to your .news-container

  5. Use .last() to find the last news item in the container and fade it out (and then .remove() to remove it completely)

Upvotes: 1

RanchiRhino
RanchiRhino

Reputation: 774

You can use something like this

<div>
<ul>
    <li>zero</li>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
</ul>
</div>

<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#news').prepend('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
var maxAllowed = 3;
$( 'li:gt(' + ( maxAllowed-1 ) + ')' ).remove();}
</script>

It will automatically remove items from bottom when one is added at top using prepend(). Have a look at this SO thread

Upvotes: 1

Related Questions