-1

The onLine checker is running fine, but I want to set 'if' and 'else' in the javascript.

Practical if the status is online... you must be transferred to another link. If the status is offline... the status must show this message 'Re-connecting...' until the device is connected. And I hope after connecting it will check again the 'if' and you normally must be transferred to assigned path.

Here is the HTML code:

<p>Current network status: <span id="status">checking...</span></p>

And here is the javascript code:

var statusElem = document.getElementById('status');

setInterval(function () {
  statusElem.className = navigator.onLine ? 'online' : 'offline';
  statusElem.innerHTML = navigator.onLine ? 'online' : 'offline';  
  if ('status'=='online') {
    window.location = "http://www.google.com/";
  }
  else {
    statusElem.innerHTML = navigator.onLine ? 'Online' : 'Re-connecting...';  
  }
}, 250);

Thanks for the time :)

jasonscript
  • 6,039
  • 3
  • 28
  • 43
Flamur Beqiraj
  • 1,957
  • 2
  • 13
  • 18

1 Answers1

1

Because you want to redirect to a new URL if you're online, I think your code can be rewritten like so

var statusElem = document.getElementById('status');

setInterval(function () {
  if (navigator.onLine) {
    // you're online. Redirect to the desired URL
    // this will also clear the interval
    window.location = "http://www.google.com/";
  }
  else {
    // not online. Update the statusElem
    statusElem.className = 'offline';
    statusElem.innerHTML = 'Re-connecting';
  }
}, 250);

EDIT

If you're opening the link in a new window, you may need to clear the interval, otherwise it will just keep executing every 1/4 second. You can stop the interval using the clearInterval method

var statusElem = document.getElementById('status');

var intervalId = setInterval(function () {
  if (navigator.onLine) {
    // clear the interval
    clearInterval(intervalId);

    // you're online. Redirect to the desired URL
    window.location = "http://www.google.com/";
  }
  else {
    statusElem.className = 'offline';
    statusElem.innerHTML = 'Re-connecting';
  }
}, 250);
jasonscript
  • 6,039
  • 3
  • 28
  • 43
  • Nice, but here is again an problem, when im online it retries x times google.com, it doesen't stop... Maybe becouse the number 250? – Flamur Beqiraj Jul 03 '15 at 02:42
  • @FlamurBeqiraj The setInterval will repeat every 250ms (1/4 second) so if you're offline it will just repeat forever. If you're online, you should be redirected to google just once (unless you're opening the link in a new tab) – jasonscript Jul 03 '15 at 02:44
  • But it is not happening so, please test it, or my browser is crashed? – Flamur Beqiraj Jul 03 '15 at 02:47
  • Sorry im a beginner but the second code is perfect like I was searching for, thanks very much ^^ – Flamur Beqiraj Jul 03 '15 at 02:50