imgkl
imgkl

Reputation: 1082

How to Display value dynamically in a div tag using JS

I doing a little project which shows the internet speed by pinging the website and shows the network speed. but the problem is I have to reload every time to get the speed. How to make the div tag which contains the value of the speed to change dynamically.

I tried to load the value of the tag to itself but it doesn't work for me.

The HTML:

<h2> <span id="speed"></span> kbps</h2>

The JS:

kbitsPerSecond has the value of the speed.

$(document).ready( function () {
  $('#speed').load('kbitsPerSecond');
refresh();
});

function refresh() {
  setTimeout ( function() {
    $('#speed').fadeOut('slow').load('kbitsPerSecond').fadeIn('slow);
    refresh();
  },200);
  }

The tag has to be reloaded dynamically

Upvotes: 1

Views: 222

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

First, you have two syntax problems.

The JQuery .load() method takes a URL as the first argument, you are passing the string 'kbitsPerSecond', which is not a URL:

$('#speed').load('kbitsPerSecond');

Your call to .fadeIn() is missing a closing quote and, if you want the fade in to happen after the .load has completed, you should not chain it after .load, but instead include it in the .load() callback:

$('#speed').fadeOut('slow').load('https://example.com').fadeIn('slow);

Now, setTimeout() is a one-time timer. Instead of making refresh() recursive, use setInterval() which is a continuous timer -- it counts to its supplied interval and then fires its callback function, then it counts again and fires again and so on. However, this will continue even after the page has finished loading, so you'll probably want to cancel the timer at some point.

Also, you don't need two separate .load() calls and a separate function as shown below:

let timer = null; // Will hold a reference to the timer
$(function () {
  timer = setInterval (function() {
    $('#speed').fadeOut('slow').load('https://example.com', function(){
      $('#speed').fadeIn('slow');
    });
  },200);  
});

// Uncomment and add the following to some callback that fires when you no longer want the timer to run
//clearInterval(timer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2> <span id="speed">TEST</span> kbps</h2>

Upvotes: 1

Related Questions