how to compare the current line and the one that appears in its place when ajax request. In particular, I want to implement such a mechanism, which will update the cryptocurrency rates and accompany it with colors. So the question is how do I compare these values

$("document").ready(function() { function get() { $.ajax({ url: 'pars.php', type: 'POST', success: function(data) { var obj = jQuery.parseJSON(data); $('.btc').text(obj.resmath1); $('.xrp').text(obj.resmath2); $('.eth').text(obj.resmath3); $('.eos').text(obj.resmath4); $('.ltc').text(obj.resmath5); $('.xuc').text(obj.resmath6); $('.bth').text(obj.resmath7); $('.dash').text(obj.resmath8); var a = $('.ltc').text(); плоды моих фантазий// if( a > obj.resmath5 ){$('.ltc').addClass('green'); // }else{ // $('.ltc').addClass('red'); // } } }); } get(); setInterval(get, 1000); }); 

The ajax request itself is just as interesting as how to implement adding a class for a specific time.

HTML

 <tr> <td><img style="width:30px;" src="images/Litecoin.png"/></td> <td>LTC</td> <td>Litecoin</td> <td class="ltc td"><center><img style="width:20px;" src="images/giphy.gif"></center></td> </tr> 
  • "and accompany it with flowers" - I recommend gladioli - Igor

1 answer 1

 $("document").ready(function() { function updateValue(elClass, elValue) { var $el = $('.' + elClass + ' span'); var oldValue = +$el.text(); var newValue = +elValue; $el.text(elValue); $el.removeClass("green red"); var class1 = (oldValue > newValue) ? "green" : "red"; $el.addClass(class1); setTimeout(function() { $el.removeClass(class1); }, 1000); } var i = 1; function get() { setTimeout(function(data){ // to simulate asynchronicity var obj = jQuery.parseJSON(data); updateValue('ltc', obj.resmath5); setTimeout(get, 1000); }, 1, JSON.stringify({ resmath5: i++ })); /*$.ajax({ url: 'pars.php', type: 'POST', success: function(data) { var obj = jQuery.parseJSON(data); updateValue('ltc', obj.resmath5); // ... } });*/ } get(); }); 
 .green { color: green; } .red { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table border=1> <tr> <td><img style="width:30px;" src="images/Litecoin.png" /></td> <td>LTC</td> <td>Litecoin</td> <td class="ltc td"> <center><img style="width:20px;" src="images/giphy.gif"></center><span>10</span> </td> </tr> </table> 

  • Yes, but it’s better to call setTimeout (get, 1000) from a callback - David Manjulā
  • @DavidManjula Possible. The question is not about that. - Igor
  • @Igor unfortunately does not work, even the text that should appear does not even appear - Emil Rotatew
  • @EmilRotatew create an example with markup - Igor
  • @Igor <tr> <td> <img style = "width: 30px;" src = "images / Litecoin.png" /> </ td> <td> LTC </ td> <td> Litecoin </ td> <td class = "ltc td"> <center> <img style = "width: 20px; " src = "images / giphy.gif"> </ center> </ td> </ tr> - Emil Rotatew