What is the best way to use JavaScript to fill in missing images with alternative HTML content?

As a provider of a service that helps users find the location of pictures, I face a challenge due to the fact that the pictures are stored on another internal site. Some users may not have access to this site as my service offers additional information. The traditional method of adding alt attributes to images does not give me enough flexibility to inform users of how they can view the pictures.

<div id=theDiv>
    <img src='http\internalSite\' + this.name + '.jpg'
    alt='Please connect to internalSite to see the picture ' + this.name + '.jpg'>
</div>

I am looking to enhance the alt text by providing a direct link to the 'internalSite' or possibly loading the connection page in an iFrame for a better user experience. However, I have found it challenging to achieve this functionality using the onError attribute of the IMG tag when the image is dynamically added to the page by script.

Is there a way for my script to detect if the picture is unavailable beforehand so that I can make a decision on what action to take?

In pseudo code:

if (isURLavailble(path)){
    loadPicture();
} else {
    loadSomethingNiceToSayPicIsntAvailable();
}

Is there a reliable cross-browser function that can be defined to check if a URL is available like isURLavailable(path)?

Answer №1

If you have broken images on your website, one way to handle them is by replacing them with login links:

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Test</title>
    </head>

    <body>

        <img src="doesnotexist">

        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script>
            // Check if an image is loaded and replace broken ones with a login link
            $( document ).ready( function () {
                "use strict";
                $('<a href="login">login here</a>').replaceAll($('img').filter( function () {
                    return !(this.complete && this.naturalHeight !== 0);
                }));
            });
        </script>

    </body>
</html>

For more information on handling broken images in JavaScript, you can refer to this answer.

Alternatively, you can dynamically set the images and handle errors like this:

var img = new Image();
img.onload = function () {
    $(img).appendTo('.image-container');
};
img.onerror = function () {
   $('<a href="login">login here</a>').appendTo('.image-container');
};
img.src = 'doesnotexist';

Answer №2

One way to verify a URL is using JQuery jqXHR requests:

$.get("urlToVerify.com").done(function () {
  displayImage();
}).fail(function () {
   showAlternativeMessageWhenImageIsNotAvailable();
});

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

Executing multiple calls with Angular's $http service and then resolving them within a loop using underscore

I am facing an issue while trying to fetch multiple data from $http inside _.each function and display the combined data in $scope.tasksData. The problem I encountered is that _.each is being executed later, causing it to return null first. Can someone pl ...

Combining audio tracks using NodeJS: A step-by-step guide

Looking to combine multiple audio files in nodejs. The audio files I have are: audio1.mp3, audio2.mp3, audio4.mp3. Here's how I want them mixed: at 0:00 seconds : add audio1.mp3 to the final mix at 0:30 seconds : add audio2.mp3 to the final mix at 00 ...

What is the best way to showcase a String variable with spaces in the value field of a form within JSP?

When working with a String variable in JSP and trying to display it in a form field, there might be an issue if the string contains spaces. Only the first word is displayed instead of the entire sentence. Below is the code snippet along with the resulting ...

Exploring the functionality of Jquery with the :active selector

Here is the code I have been working on: $('#ss a:active').parent().addClass('ss-active'); It seems like my code is not functioning as expected. Can you help me figure out how to achieve my desired outcome? Additionally, I want the bu ...

Encountering an unexpected error with the InvalidCharacterError in IE11 when using VEE Validate in conjunction with Vue.js and babel-p

Encountering an issue in IE11 where I receive an InvalidCharacterError when attempting to validate a form using vee validate in vue.js. It seems like it might be related to a polyfill error, but I'm uncertain. I have tried debugging by removing certai ...

How can I eliminate the border from the last child in a row within a responsive framework?

Put simply, I am trying to target not only the last child in a parent div, but also the last item in a row that adjusts based on screen size. I have a row of 4 elements (divs) with borders on all but the last one using :last-child. However, when the screen ...

Organize the attributes of components on the following line in Visual Studio Code

Is there a method to configure the VS code formatter for Angular 2+ templates to ensure that attributes are wrapped in a new line? I prefer this formatting: <app [input1]="input1$ | async" [input2]="input2$ | async" (inputChanged)="set ...

Does CausesValidation validate all validators, including validation groups?

I have encountered an issue with my web page where I have 3 separate validation groups, but when I attempt to submit the form, I want all of the groups to validate simultaneously. It appears that using causesValidation="true" on the button does not trigge ...

The validation process is still failing even though the correct credentials have been entered

I'm diving into the world of Javascript and DOM today, but I've hit a roadblock. Can you take a look at this code snippet and help me figure out what's causing me to always end up in the else block, no matter what I input in the text field? ...

Ensuring Consistent HTML5 Page Layout Across Various Browsers Using CSS

Hey everyone, I recently created an HTML5 page and utilized the <section> tag. However, I'm encountering issues with the CSS file I'm using. It seems to work perfectly on Firefox, but the layout is all over the place when viewed on Chrome a ...

Tips for scrolling ion-items vertically to the bottom and top using arrow icons in Ionic 4

I'm developing an Ionic 4 app with Angular and looking to incorporate Up and Down Arrow buttons for vertical scrolling from top to bottom and vice versa. ...

What is the best way to position the content area to the right of the menu on my website?

Hey there! I'm currently facing an issue with Bootstrap 4 where my content area is appearing below the vertical navbar instead of next to it on the right side. Any suggestions on how to adjust my code to fix this? Thanks in advance! <div class=&qu ...

What's the reason behind express-rate-limit not performing as anticipated?

There seems to be an issue with the enforcement of the rate limit I specify in my code. Instead of lasting for 35 minutes as intended, it only lasts for about 20 seconds. Additionally, continuously making requests seems to reset the time limit, which is un ...

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

Why is Handlebars {{body}} not rendering my HTML tags properly?

I am perplexed by the fact that the example in the other file is not showing. While working on a CRUD project with Mongo, Express, and Node, I encountered an issue. The code wasn't functioning as expected, so I paused to figure out why. <!DOCTYPE ...

Modify the arrow design for the expansion panel's default arrow style

Looking to customize the design of an angular expansion panel? Check out the images below for inspiration: Before Customization: After Customization (Not expanded): After Customization (Expanded): Wondering how to achieve this look using angular materi ...

Are multiple instances of ajax being executed within the modal?

Currently, I am working on a feature that requires an Ajax request. To begin with, the process involves opening a modal by clicking a button with the class '.open-email-modal'. Within this modal, there are two input fields to enter registration d ...

What is causing Ajax to fail in connecting to the server?

When trying to submit a simple ajax form and send a response to my server, I keep getting the following error message : Forbidden (CSRF token missing or incorrect.): /designer/addOne/ [31/Jul/2017 12:49:12] "POST /designer/addOne/ HTTP/1.1" 403 2502 Alt ...

Creating a visually appealing layout by dividing HTML content into two columns within a WebView

Utilizing WebView in my application to display html content for reading ebooks presented a challenge during development. After parsing the ebook and converting it into an html string, I load this string into the WebView component. myView.setVerticalScro ...

Leverage the power of jQuery to fetch data from a PHP script connected to a MySQL database

It might be a bit confusing, so let me clarify. I'm working on a form where users input a ticket and it gets assigned to a technician based on the service they offer. I have 3 text fields: username, email, and description of the problem. The next fie ...