1

I am using jqueryUI/jquerymobile for an WebApp. There is a button which should check if the user is connected to the internet or not. Wether he is or not the href of the link should change. I tried the following but it does not work. Any ideas why? It opens the link to http://test.com every time, no matter if online or offline.

<script type="text/javascript">

    function OnClick () {
        if ('onLine' in navigator) {
            if (navigator.onLine) {
                window.location = "http://test.com/";
            }
            else {
                window.location = "test.html";
            }
        }
        else {
            alert ("Your browser does not support the onLine property.");
        }
    }

</script>

<li class="ui-corner-none nav2"><a href="http://test.com/" onClick="OnClick ()">Link</a></li>
Max
  • 608
  • 1
  • 7
  • 23

1 Answers1

1

I don't know the logics behind it - but my guess is that the click on the "link" will be initiated first (aka the browser follows the link first) and than the OnClick event fires (which will do nothing because it isn't on the same page anymore).

Read more about it: JavaScript function in href vs. onclick

My fix would be to check upon pageload if you are connected to the internet and change the 'href' attribute of the link.

$(function() {
    if ('onLine' in navigator) {
        if (navigator.onLine) {
            $("li.nav2 a").attr("href", "http://test.com/")
        }
        else {
            $("li.nav2 a").attr("href", "test.html")
        }
    }
    else {
        alert ("Your browser does not support the onLine property.");
    }
});

another quicker fix would be

<li class="ui-corner-none nav2"><a href="http://test.com/" onClick="return OnClick ()">Link</a></li>

See: HTML tag <a> want to add both href and onclick working

Community
  • 1
  • 1
Biketire
  • 2,019
  • 1
  • 23
  • 41
  • Thanks but it does nor work entirely. The test.com website works, even if i change the href in the a tag . But if i switch to offline the browser wants to open test.com again and not test.html – Max Dec 06 '13 at 09:41