Displaying image titles when the source image cannot be located with the help of JavaScript or jQuery

I am currently facing an issue where I need to display the image title when the image is broken or cannot be found in the specified path.

At the moment, I only have the options to either hide the image completely or replace it with a default image.

$('img').on("error", function() {
  $(this).attr('src', '/images/missing.png');
});

// Alternatively, hide them
$("img").on("error", function() {
  $(this).hide();
});

However, these solutions do not meet my requirements. If anyone has any ideas on how to display the image title when the image is broken using JavaScript or jQuery, I would greatly appreciate your assistance.

Answer №1

Swap out your image tag with different elements using the replaceWith function within error.

$('img').on("error", function() {
  var title = $(this).prop("title");
  $(this).replaceWith("<span>" + title + "</span>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://stackoverflow.com/testimg.jpg" title="Your title"></img>

Answer №2

$(document).ready(function() {
 
   
   $("img").on("error", function () {
    $(this).attr("src", "https://lh3.googleusercontent.com/-bRgqJ3P_4k8/AAAAAAAAAAI/AAAAAAAAAjQ/eYIXbdyNxKM/photo.jpg?sz=48");
});
});
<!DOCTYPE html>
<html>
<head>
<title>Try jQuery Online</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</head>
<body> 
 <img  
     src="/media/cc0-images/grapefruit-sl.jpg"
     alt="Grapefruit slice atop a pile of other slices">

</body>
</html>

Answer №3

After conducting some research, I have discovered a simple method to achieve this task. All we need to do is insert the image into a Div element, allowing us to access the parent DIV Id of the image. We can then use the following code snippet to append the title to this parent div.

var images = document.querySelectorAll('img');

for (var i = 0; i < images.length; i++) {
  images[i].onerror = function() {
    $("#"+this.parentElement.id).append(this.title)
    this.style.display='none';
  }
}

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

Ways to incorporate a loading feature in javascript, jquery, and php as it runs?

I have created a form that, when clicked on, returns a value within the page. Below is my form. When the form is submitted, it takes some time to process. I would like to display a loading message while the code is being executed. Here is my form: <ht ...

Unlocking the Page object in asp.net from a Static method

I'm currently working on a website that includes a dropdown list feature to select different packages. The challenge I'm facing is displaying the price of the selected package without causing a postback every time a selection is made. To tackle t ...

Is it possible to implement a unique style exclusively for my application's components?

Recently, I've been trying to apply a universal style rule to my entire app similar to this: div { width: 100%; } At first, everything seemed to be working perfectly. However, when I began integrating third-party components that have their ow ...

Error: Unable to modify the value of a protected property '0' in the object 'Array'

I am facing a challenging issue with implementing a Material UI slider in conjunction with Redux. Below is the code for the slider component: import { Slider } from '@material-ui/core' const RangeSlider = ({handleRange, range}) => { ...

Issue with SVG marker not functioning properly when hovered over

I am having an issue with buttons containing SVG elements, here is an example code snippet: <button> Checkout <ArrowSvg /> </button> The ArrowSvg component looks like this (with the line having a class of "svg-line"): <svg fill=&quo ...

How can I retrieve an array from an object containing both a property and an array in TypeScript?

One of my objects always consists of a property and an array. When I use the console.log(obj) method to print it out, it looks like the following example: ProjectName: MyTest1 [0] { foo: 1, bar: 2} [1] { foo: 3, bar: 4} [2] { foo: 5, bar: 6} Alternat ...

fancybox thumbs will never function properly

I recently made the switch from using PrettyPhoto to FancyBox for my gallery, which utilizes Isotope for filtering and animations. However, I am encountering an issue where the images appear but the thumbnails are missing. In the developer tools, there is ...

Distributing actions within stores with namespaces (Vuex/Nuxt)

I'm encountering an issue with accessing actions in namespaced stores within a Nuxt SPA. For example, let's consider a store file named "example.js" located in the store directory: import Vuex from "vuex"; const createStore = ...

Encountering difficulty with displaying a 404 error using Cloud Functions on Firebase Hosting

I am currently facing an issue with handling a custom 404 error using Firebase Hosting and Functions. The code I have provided below works perfectly fine on localhost, but once deployed, Firebase Hosting returns a 500 error instead of the expected 404. ht ...

The Node.js application gracefully exited with code 0 with Forever

Running a Node.js Express app on CentOs 6.5 using the root account: root@vps [/home/test/node]# npm start app.js > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aedacbdddaee9e809e809f">[email protected]</a> s ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Simple user interface height to occupy the entire browser window

Adding Tabs Dynamically ... I am attempting to design a layout using this example ... however, the issue is that the page does not utilize the full height and width of the available space... I have attempted adjusting the width and height to 100% of the ...

Dynamic background image that fills the entire webpage, adjusts to different screen sizes, and changes randomly

Currently, I am working on designing a web page with a dynamic background image that adjusts responsively in the browser without distortion. The challenge is to randomly select an image from an array using jQuery. Unfortunately, my knowledge of jQuery is ...

Enhance your webpage with a stunning background video

I'm trying to add a background video that covers the entire screen but maintains a height of 400px, similar to the one shown here. Is there a way to achieve this without using JavaScript? Below is the HTML code I currently have: <div class="pr ...

Manage the placement of elements using CSS

Having an issue here. The blue-colored elements are showing up vertically, but I want them to be displayed horizontally. I've tried various methods but haven't been able to solve the problem. Providing just the code for the items below due to len ...

Assistance Required for Troubleshooting Error in Codeigniter Ajax

Hey there, I'm a newcomer to CI and I've been searching the web for a tutorial that actually works, but so far no luck. Can someone please assist me with this code: How can I modify the code to allow for submitting an entry to the database via a ...

Is there a way to arrange elements in an array based on the second value in each nested array?

I need help organizing an object {a: 1, b: 20, c: 3, d: 4, e: 1, f: 4} into the following format {a: 1, e: 1, c: 3, d: 4, f: 4, b:20} (sorting the object numerically in ascending order) using a specific set of steps. Here are the steps I have outlined: ...

Regularly check in with the server via ajax calls

I have a page that needs to send periodic "background" ajax requests after it is loaded. These requests should be sent at specific time intervals. Would using cron be the best option for this task, considering that I have never used it before? Are there a ...

Why do some button clicks not trigger a page refresh in JavaScript?

Hey there, I have a situation where I have two buttons - one to add a dog to the dog list and another to clear the entire list. Both buttons are functioning properly, but I'm having an issue with only the OnSubmit button refreshing the page. The dog ...

What is the best way to retrieve a promise from several promises?

Every time I check the console, I see the following: teamsUpdated2 addUserToProjects deleteUserFromProjects However, they should be displayed in a different order. var result = teamService.addOrDeleteUser(userId, newTeams, deleteTeams); result.then(fun ...