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

The styling of divIcons in React Leaflet Material UI is not applied as expected

When using divIcon in React Leaflet to render a custom Material UI marker with a background color prop, I noticed that the background style is not being applied correctly when the marker is displayed in Leaflet. Below you can find the code for the project ...

Definitions for TypeScript related to the restivus.d.ts file

If you're looking for the TypeScript definition I mentioned, you can find it here. I've been working with a Meteor package called restivus. When using it, you simply instantiate the constructor like this: var Api = new Restivus({ useDefaultA ...

How come certain rectangles vanish when one rectangle completely fills the space?

Currently, I am encountering an issue with CSS paint worklet and I am trying to determine if it's a browser bug or an error on my end. In the worklet, I am drawing multiple rectangles. Strangely, when one rectangle covers the entire area, the others s ...

Create a Vue application that is built on modules which could potentially be absent

I am currently developing a Vue+Vite app with module-based architecture. I have several Vue components and some parts of the app are functioning correctly. However, I want to ensure that the missing components are not imported or used in the application. H ...

Maintaining datatype integrity in MongoDB Stitch when decrementing with update statements

Using a MongoDB Stitch function, I have two collections: communities and posts. Whenever a new document is inserted in the post collection, I need to increment the summary.postCount in the communities collection by +1. Similarly, when the status of a post ...

CSS animations can make the navigation bar vanish into thin air

I recently started implementing CSS3 animations from the Animate.css library and I must say, they really enhance the look and feel of my website. The animations pair perfectly with WOW.js to create stunning effects. However, I have encountered a minor iss ...

The CSS styles are not being applied correctly in the HTML document

I have this snippet in my .css file: .attachment-label { font-size: 10px; font-style: italic; color: rgba(0,0,0,.5); } When I try to use it in my HTML like this: <div class="card-body"> <span class=" ...

I am a newcomer to HTML and I am eager to display the selected options from a <select> element

Can someone help me display the selected licorice flavor, chocolate color, and topping? For example: "Green apple, white, christmas sprinkles." I'm not sure if assigning a numeric value to each option is necessary. I did it on a whim. Please suggest ...

Instructions for converting a readonly text field into an editable one using JavaScript

I'm trying to make it so that when the button (with id name_button) is clicked, the text field (with id name_text_field) becomes enabled. However, my current code doesn't seem to be working. Here's a snippet of my HTML: <input type="tex ...

Submitting the form does not result in the textbox being cleared

I have been attempting to clear the txtSubTotal text box upon clicking the PROCEED button, but it seems that my efforts have been in vain despite trying various code examples, including those from SO. btnProceed/HTML <input type="submit" name="btnProc ...

"Transitioning from jQuery to Vanilla Javascript: Mastering Scroll Animations

I'm seeking guidance on how to convert this jQuery code into pure Javascript. $('.revealedBox').each(function() { if ($(window).scrollTop() + $(window).height() > $(this).offset().top + $(this).outerHeight()) { $(this).addCla ...

Dynamic styling based on conditions in Next.js

After a lengthy hiatus, I'm diving back in and feeling somewhat disconnected. In short, I have encountered a minor challenge. I successfully created a navigation menu pop-out that toggles classname based on the isActive condition in React. However, I& ...

A Step-by-Step Guide to Successfully Clicking on a Checkbox Using Selenium and Python

Hello everyone, I'm facing an issue with clicking a checkbox. Here is the code for the checkbox: <label class="has-checkbox terms"><input name="order[terms]" type="hidden" value="0" /><input class="checkbox" type="checkbox" value=" ...

The functionality of jQuery.hover with AJAX is malfunctioning

I am facing an issue with my jquery hover combined with $.post method. My initial intention was to create a series of select buttons where hovering would trigger a change in the image being displayed (the image path would be loaded via $.post). The image ...

After the execution of the script by V8, which phase will be initiated first?

Scenario // test.js setTimeout(() => console.log('hello'), 0) setImmediate(() => console.log('world')) Simply execute node test.js using node v12.12.12 on an Intel MacBook Pro. The output may vary: hello world Sometimes it is: ...

I'm encountering an issue with the dropify plugin where the data-allowed-file-

While using the dropify library to style file upload elements in my form, I ran into an issue with the data-allowed-file-extensions parameter not working as expected. Despite specifying allowed file extensions like "png jpg jpeg", the validation for input ...

What is the most efficient method for examining dependencies in Yarn 2 (berry)?

Is there a way to check for vulnerabilities in Yarn 2 dependencies? In Yarn 1.x, you could run yarn audit, similar to npm audit. However, this command is not available in Yarn 2. According to this issue on the Yarn berry Github, it may not be implemented ( ...

Utilizing JQuery for real-time total updates

When a new div is created by clicking a button, I want to dynamically maintain an order system where the first div is labeled as 1 of 1, then as more divs are added it should change to 1 of 2, and so on. If a div is deleted, the numbering should reset back ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...

Prevent the ability to drag and drop within specific div elements

Having trouble disabling the sortable function when the ui ID is set to "comp". Can't figure out what's going wrong, hoping for some assistance here. $(".sort").sortable({ // start sortable connectWith: ".sort", receive: function ...