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

I have a webpage that is being updated via ajax. It downloads updated news feeds every 1 minute. I want to create javascript that detects an incoming date field and places a strong tag around it. Here's an html sample that gets a 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 basic javascript that updates it, but it runs only once. How do I make javascript detection if there is anything in the "results" element and act accordingly.

+6
source share
3 answers

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

 $( 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>'); } }); }); 
+1
source

If you are using jQuery (you should tag your question with jquery tag) then you want to use such a solution using $.ajaxComplete . If you use a different infrastructure, there are other ways to do it the same way.

 $(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 either A) to make an assumption based on the result saying that it promises a new one or B) comparing it with the previous version. You can use $.ajaxSend to save the changes for method B.

If you go by method A , you can just keep track of the maximum date and do something only if the date is longer, and then update the maximum date with this.

+2
source

If you do not want to use the Ajax success callback, you can use the DOMSubtreeModified event. eg

 $('div.results').bind("DOMSubtreeModified", function () { alert('changed'); }); 

This will be triggered when the contents of div.result change. int is an event, you can do whatever manipulations you want with div.date

+1
source

Source: https://habr.com/ru/post/956648/


All Articles