Bob Bob - 21 days ago 7
CSS Question

Based on internet connection change color of button to green or grey

I want the button itself to change its color when online(based on internet connection) to green otherwise gray.

I have a JS fiddle which gives a solution to click the button and we can see if we are online/offline by an alert.

Can someone please help

HTML:

<div data-role="page" id="index">
<div data-theme="a" data-role="header">
<h3>First Page</h3> <a href="#second" class="ui-btn-right">Next</a> </div>
<div data-role="content"> <a data-role="button" id="check-connection">Check internet connection</a> </div>
</div>


jQuery:

$(document).on('pagebeforeshow', '#index', function() {
$(document).on('click', '#check-connection', function() {
var status = navigator.onLine ? 'online' : 'offline';
(alert(status));
});
});


See JSFiddle.

Answer

Here is the working fiddle: http://jsfiddle.net/dn7zjm41/

I just added an if statement:

if(status==="online") {
  $("#check-connection > span").css("background-color", "green");
} else if(status==="offline") {
  $("#check-connection > span").css("background-color", "gray");
} else {
  // the code for another scenario
}

And if you want an automatic run without click event - here it is: http://jsfiddle.net/f6paa9xy/

In this case your Javascript should look like this:

$(document).on('pagebeforeshow', '#index', function() {             
  var status = navigator.onLine ? 'online' : 'offline';
  alert(status);
  if(status==="online") {
    $("#check-connection > span").css("background-color", "green");
  } else if(status==="offline") {
    $("#check-connection > span").css("background-color", "red");
  }
});

Hope it helps