Is there a way to update my image based on whether I am connected to the internet or not?

        <script>


            function checkConnection() {

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

            }

            </script>

Introducing a dynamic image swapping feature based on the user's online or offline internet connection status.

Answer №1

Here is a way to customize a function:

 window.addEventListener("online" , _=>{
            //define action for online event
        })
        window.addEventListener("offline" , _=>{
            //define action for offline event
        })

For example, you can use the following code snippet:

        
 

            
 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 when online
 changeimage(true)
            })
            window.addEventListener("offline" , _=>{
                //set image when offline
 changeimage(false)
            })
            
            // initial setup
             changeimage(navigator.onLine)
<img id="wifi-image" src="" alt="online-mode">

Answer №2

It seems that you are working with the Cordova tag, which indicates that your project is a mobile app.

One way to store images in the cache is by utilizing imgcache

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

However, this approach may not be effective if the app has never been connected to the internet, as there won't be a file for reference.

If you encounter any challenges, feel free to reach out.

Cheers!

Answer №3

When using HTML:

<img id="imageID" src="photo.jpg"/>

When using JavaScript:

if(navigator.connection.type == Connection.NONE){
   console.log("The device is offline");
    //You can now display the image from your local folder
    $("#imageID").attr("src","photo.jpg");

}else{
   console.log("The device is online");
   //You can now load the image from the internet like this
   $("#imageID").attr("src","https://website.com/photo.jpg");
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Feature exclusively displays malfunctioning image URLs for the web browser

Hello everyone! I've been diving into learning JavaScript and recently attempted to create a function that randomly selects an image from an array and displays it on the browser. Unfortunately, despite my efforts, all I see are broken link images. Her ...

What steps can be taken to ensure the visibility and accessibility of two vertically stacked/overlapped Html input elements in HTML?

I have encountered a challenge with my HTML input elements. There are two input elements that overlap each other, and I would like to make both inputs visible while only allowing the top input to be editable. I have tried several approaches involving z-ind ...

Generating a collection of objects containing a variable number of attributes

I want to generate an array of objects filled with random properties. Each object should have the following structure: { systemStar: "something random", planets: ["random1", "random2", etc]} Here's the current code I a ...

Is there a Ruby gem similar to Readability that anyone can recommend?

Readability is a nifty JavaScript tool that magically transforms a cluttered HTML page into a more user-friendly format. I'm on the hunt for a Ruby implementation or something along those lines - does anyone know of a library that offers similar funct ...

The functionality of the page becomes disrupted when multiple timers are used after the setInterval function is executed in

My webpage fetches multiple data for a table, with one of the columns displaying date and time values from which countdown timers run. Each row has its own timer and functions correctly. However, when I added JavaScript code to refresh the table every 10 ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

Experimenting with jQuery's .hide() and .show() functions with an alert message confirming that the div is not

Below is some simple code to demonstrate an issue: $('.myDiv').click(function() { $('.anotherDiv').hide(); alert('pause the ui'); $('.anotherDiv').show(); }); After clicking on the .myDiv element, the ...

Disregard all numbers following the period in regex

I have developed a function to format numbers by adding commas every 3 digits: formatNumber: (num) => { return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') }, The issue with this function is that it also add ...

What is the best way to position the label above the input text in a Material UI TextField component with a Start Adornment?

Struggling to figure out the right Material UI CSS class to style a reusable TextField component? You're not alone. Despite tinkering with InputLabelProps (specifically the shrink class), I can't seem to get it right. Here's the code snippet ...

I am looking to save the session value into the search box of the appTables application by utilizing jQuery

Is there a way to save the session value in the search box of appTables by using jQuery? <?php $session = \Config\Services::session(); ?> <script type="text/javascript"> $(document).ready(function () { var searc ...

What is the best way to track down the source of a CSS rule?

A website built on .asp was passed down to me, and I was tasked with reorganizing forms in tables to the sidebar. Most pages were successfully updated, except for one stubborn page that seems to be ignoring my CSS changes and using values from an unknown s ...

Guide on How to Show Only the Initial Word of an H2 Header Using JavaScript or CSS

Is there a way to display only the first word from an h2 heading? For instance: In the website's source code, it would appear like this <h2> Stackoverflow is an Ideal Place</h2> But on the live website, it should be displayed like this ...

Issue with displaying background image in mobile device despite successful display in browser and Chrome tools on Angular 18

Revamping my personal website (www.coltstreet.com) led me to explore media queries for displaying different background images. Testing on desktop and via Chrome tools showed positive results, but the real challenge arose when viewing the site on my actual ...

Exploring the universal scope in NodeJS Express for each request

I am working with a basic express server that is in need of storing global variables during request handling. Specifically, each request involves multiple operations that require information to be stored in a variable like global.transaction[]. However, u ...

Issue with displaying checkboxes in the dataTable table

I am currently working with dataTables and encountering difficulties displaying checkboxes on my tables. Below is the code that I have: <table id="employeeList" class="table table-sm table-bordered table-hover" cellspacing="0" width="200%"> &l ...

How can I ensure that my CSS code functions seamlessly across all versions of Internet Explorer from IE6 to the latest release?

I need a solution for getting this CSS code to function properly across all versions of Internet Explorer, from IE6 to the most recent version. body:first-child * { margin-top:0 !important; } body:last-child * { margin-bottom:0 !important; } Any ...

Is it possible to capture the child element's id?

After loading several images onto the page, I hide them using 'display:none': <div id="cont-img"> <img class="lista-img" src="list/1.png" id="v1" /> <img class="lista-img" src="list/2.png" id="v2" /> <img class=" ...

Send data to MySQL database with AJAX submission

Upon attempting to submit a form to my MySQL database utilizing jQuery (AJAX), I encounter the message "failed" that I programmed in JavaScript when clicking the submit button. It seems that there might be an issue with my JavaScript syntax. HTML/JavaScri ...

Trouble with clearTimeout function

//Account Creation - Register Button Event $('#registerCreateAccount').on('click', function() { var username = $('#registerUsername').val(); var email = $('#registerEmail').val(); var age = $('#regis ...

Tips for replicating PaddingTop using Grid Material UI and populating blank rows at the beginning

Imagine we are working with a Grid component const App = () => { const useStyles = makeStyles(theme => ({ root: { flexGrow: 1 }, paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.tex ...