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

An HTML attribute with a blank value will not display the equals sign operator

jQuery can be used like this: $select.append('<option value="">All</option>'); This code appears to insert the element in HTML as follows: <option value>All</option> However, what is intended is to append the elemen ...

What is the best way to generate a variable amount of div elements with constantly changing content using Angular2?

I'm not entirely sure on the process, but I believe ngFor would be used in this scenario. Essentially, my goal is to generate the following div multiple times, with each iteration updating the value inside the brackets from 0 to 1, 2, and so forth... ...

Issues arise when implementing a sticky position using CSS with incomplete functionality

I want to create a website with a menu bar that stays at the top even on long pages. However, when I use position: sticky in CSS, the menu disappears after scrolling a certain distance. Does anyone know how to fix this issue? HTML: <nav> <ul cla ...

Update the state in the componentDidMount lifecycle method

Embarking on a project using React to hone my skills, but encountered an error while trying to populate an array with data from a JSON file in the ComponentDidMount() hook. It seems this issue stemmed from a previous error: cannot read property 0 of undef ...

Exploring the world of WebSockets and Socket.io

Recently many online games, like , have started using WebSockets to create real-time MMORPGs. I'm curious about how to develop a node.js program that can manage connections from browsers using WebSockets. Here is an example of browser code: <!DOC ...

Arrange divs in a stack fashion

Currently, I have a table-styled three-column set of divs. I would like these columns to stack vertically on mobile devices. I think this can be achieved using the float method, but the titles and descriptions for each column are in separate rows (divs), ...

Create an HTML table row that includes a value along with its related sibling and parent values

I need to create an HTML table that compares segments in a JSON object. The format should display the segments along with their measures organized by domain group and vertical: ------------------------------------------------------------------------------ ...

Best practices for utilizing child component methods within a parent component in VUE

I am working with the ImageUpload.vue component, which is a straightforward Bootstrap modal containing a few methods. I am currently exploring the best approach to utilize one of these methods. Could it be implemented like this: const app = new Vue({ ...

Adding HTML components to an image with adjustable dimensions

A graphic designer has provided us with an image featuring three selection boxes. I implemented the necessary HTML elements and CSS to display three overlapped selection boxes on top of the image, using pixel values for positioning. However, the original ...

Position icons and images on the right side, and the textarea on the left side of the page (using Twitter

Summary: Here is the desired end result shown in the image below. Alternatively, you can refer to the JSFiddle. Ideally, only CSS should be used without changing the DOM structure. The icons need to be aligned completely to the right using the .pull-right ...

Inject nested controller dynamically

I am working on a straightforward ASP.NET MVC application that includes an ng-controller. I am trying to inject another ng-controller inside this controller using a partial view, but I'm having trouble getting the binding to work correctly. You can s ...

Unable to transfer bootstrap form data from the view to the controller due to issues with bootstrap validations

Scenario I have integrated a bootstrap form into my codeigniter application with bootstrap validation to ensure data accuracy. I want the submit button to work properly so that users can successfully submit the form and be redirected to the action page ...

Changing HTML elements dynamically within an ng-repeat using AngularJS directives

I have devised an angular directive where I execute an ng-repeat. The fundamental purpose of this directive is to interchange itself with a distinct directive that depends on a value forwarded into the original directive: <content-type-directive type=" ...

Error: The Vue bind object property cannot be read because it is undefined in the class binding

I'm attempting to associate a class with an object property, but I encounter an issue when trying to trigger the @click event on the list object - the console states that it cannot read the isSelected property of the object. My goal is to activate a c ...

Change a reactive variable based on an event

I am currently working on a file upload feature in my application. Template.uploadFile.events({ 'change .set-file': function ( event, template ) { var file = event.currentTarget.files[0]; [...] } }); My goal is to read each row fro ...

Mastering the art of crafting form elements with jQuery

My code is looking like this: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function afterText() { var textElement = document.create ...

Are there any JQuery events that can detect alterations in the list of children elements within an element?

Is there a JQuery event available that can detect changes in the size of an element collection, such as growth or reduction resulting from adding or removing child elements? ...

Show a dynamic modal with a widget displayed inside

I am facing an issue with my Angular.js website that is filled with a multitude of widgets. Each widget consists of a template.html file paired with a controller.js file to form an angular module. These widgets are utilized on a dashboard where users have ...

The function react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_4__.jsxDEV(...) is not recognized

For my react-redux project, I utilized json-server as the server for managing orders. The status of each order is saved in the state within UiReducer and is then accessed in the "OrderStatusPage". The current NODE_ENV configuration is set to "development". ...

Creating JSON arrays with JavaScript and jQuery

User Information var Users=[{"Id":1,"FirstName":"John"},{"Id":2,"FirstName":"Emily"}] Call Information var CallInfo=[{"Id":1,"PercentageCalls":"22 %","TotalTime":"60:24 minutes","PercentageTime":"0 %","AvgTime":"0:22 minutes"},{"Id":2,"PercentageCa ...