Reputation: 513
I want to bind a script to a click answer to tell user when there is no internet connection. Example is when the user is on page1.html and clicks on a link that should take him to page2.html and there is no internet connection an alert should pop up and stop the url action for opening page2.html. i have this script but it works only when the page loads
var online = window.navigator.onLine;
if (!online){
alert('You are not currently connected to the internet. Please try again later.');
}
Upvotes: 0
Views: 242
Reputation: 108
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
var hrf=$(this).attr('href');
var online = window.navigator.onLine;
if (!online){
alert('You are not currently connected to the internet. Please try again later.');
}
else{
window.location.href=hrf
}
})
})
Upvotes: 0
Reputation: 7919
Call a javascript function on click of button and paste your code inside that function.
Html
<button onclick="check()">Go to Page 2</button>
Javascript
function check(){
var online = window.navigator.onLine;
if (!online){
alert('You are not currently connected to the internet. Please try again later.');
} else{
alert("you are online");
}
}
Upvotes: 0
Reputation: 3601
To do this you would add a click event listener to all the links on the page. Then in the click handler you check if the client is offline. If that's the case the event is canceled and we show an alert message to the user.
An implementation of this will look something like:
var links = document.querySelectorAll('a')
for (var i = 0; i < links.length; i++)
links[i].addEventListener("click", handle, false);
function handle(e) {
if(!navigator.onLine) {
e.preventDefault();
alert('You are offline!');
}
}
Upvotes: 1