简体   繁体   中英

How can i change my image when connection to internet is fired offline or online,

        <script>


            function myFunction() {

                if (navigator.onLine) {
                    swal("Great News" , 'Congratulation your connection is online', "success");
                } else {
                    swal("Sad News" , 'Can you please connect to the internet to login', "error");
                }

            }

            </script>

I would like to add a function whereby the image is changed depending whether the users connection to the internet is offline or online

you can set a custom function like

 window.addEventListener("online" , _=>{
            //set image online
        })
        window.addEventListener("offline" , _=>{
            //set image offline
        })

like

 var img1 = document.getElementById("wifi-image") function changeimage(online){ if(online) { img1.src ="online-wifi.png" img1.alt ="online-wifi.png" } else{ img1.src ="offline-wifi.png" img1.alt ="offline-wifi.png" } } window.addEventListener("online" , _=>{ //set image online changeimage(true) }) window.addEventListener("offline" , _=>{ //set image offline changeimage(false) }) // at start changeimage(navigator.onLine) 
 <img id="wifi-image" src="" alt="online-mode"> 

As I can see that you have mentioned Cordova tag, So I'm assuming that it is for a mobile app.

You can store the image in the cache by using imgcache

https://github.com/chrisben/imgcache.js/

but this will not work if your app has not connected to the internet even once because then it'll not have a file for reference.

Let me know if you find any difficulties.

cheers

in HTML :

<img id="imgID" src="img.png"/>

in JavaScript :

if(navigator.network.connection.type == Connection.NONE){
   console.log("device is offline");
    //you can now call picture from your folder
    $("#imgID").attr("src","img.png");

}else{
   console.log("device is online");
   //you can now call picture from internet like this
   $("#imgID").attr("src","https://website.com/img.png");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM