Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a persistent javascript where it updates when content is constantly updated via ajax?

I have a webpage that updates via ajax. It loads updated news feeds every 1 minute. What I want to do is create a javascript that detects the incoming date field and put a strong tag around it. Here's a sample of the html that gets feed through:

<div class="results">
  <div class="article">
    <div class="date">jan 8, 2013</div>
    <p>Some content here</p>
  </div>
  <div class="article">
    <div class="date">feb 8, 2013</div>
    <p>Some content here</p>
  </div>
</div>

I can write the basic javascript that updates it, but it only fires once. How do I go about making javascript detect if there is anything changed in the "results" element and act accordingly.

like image 298
Patoshi パトシ Avatar asked Oct 24 '13 13:10

Patoshi パトシ


2 Answers

If you're using JQuery (you should tag your question with the jquery tag), then you want a solution like this using $.ajaxComplete. If you're using some other framework, there are other ways to go about this similarly.

$(document).ajaxComplete(function() {
  $(".results .date").each(function() {
    var strong = $('<strong>').text($(this).text());
    $(this).empty().append(strong);
  });
});

// for this test, only to demonstrate, manually trigger an ajax complete event
function test() {
  $(document).trigger('ajaxComplete');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="results">
  <div class="article">
    <div class="date">jan 8, 2013</div>
    <p>Some content here</p>
  </div>
  <div class="article">
    <div class="date">feb 8, 2013</div>
    <p>Some content here</p>
  </div>
</div>
Test: <button onclick="test()">Trigger JQuery Ajax Complete Event</button>

The only way to detect a change in the results is to either A) make an assumption based on the result saying that it promises it's new or B) comparing it to the previous version. You can use $.ajaxSend to stash the changes for method B.

If you're going by method A, you could just keep track of the max date, and do something only if the date is greater, then update the max date with that one.

like image 98
TylerY86 Avatar answered Sep 28 '22 08:09

TylerY86


Can you attach a listener to the Ajax (either .complete() or .ajaxStop()), then get all dates and compare them to today`s date. If they match make the date bold. Something like this:

$( document ).ajaxStop(function() {
    var today = new Date();

    $.each( $('.article .date'), function( i, el ){
        var el_text = el.text();
        if(el_text == today.toLocaleFormat('%b %d, %Y')) {
            el.html('<b>' + el_text + '</b>');
        }
    });
});
like image 28
Petko Kostov Avatar answered Sep 28 '22 10:09

Petko Kostov