Handling image errors in jQuery for responsive design queries

Images on my website change based on the screen size using media queries. I am looking for a way to handle errors that may occur using jQuery. I want to display a text message if the image fails to load.

Here is the code I have so far:

<div class="container">
<div class="row">
    <div class="col-xs-12">
        <img class="img-responsive center-block" id="notice_banner" alt="" src="css/images/banner.png"/>
    </div>
    <div class="col-xs-12">
        <p id="altText" style="display: none">
            This is a text!
        </p>
    </div>
</div>

CSS code:

/* xs */
img {
content:url("images/small_banner.png");
}
/* md */
@media (min-width: 768px) {
img {
    content:url("images/large_banner.png");
}
}

javascript code:

$(document).ready(function() {
$("img").on("error", function() {
    $("#altText").show();
});
});

I am facing an issue where it can detect errors for images from the original src attribute, but not for images loaded through media queries.

Does anyone have a solution for this problem?

Answer №1

It has been noted in a comment that the content property is not fully supported outside of the pseudo-elements :before and :after. Currently, only Chrome supports it for any element. Additionally, there is an issue with CSS errors not triggering JS events, which means that if an image linked in CSS fails to load, JS will not detect it.

One possible solution is to listen for the resize event and, if the window size crosses a threshold set in a media query, take action accordingly (e.g. change the src attribute of the image). When this change is made within JS, it can be properly detected.

Here is an example implementation:

$(document).ready(function() {

  $("img").on("error", function() {
    $("#altText").show();
  });

  function resizeActions() {
    var windowWidth = $(window).width();
    if (windowWidth < 768) {
      $("#notice_banner").attr("src", "//placehold.it/100x100");
    } else if (windowWidth >= 768) {
      $("#notice_banner").attr("src", "fake-url-path");
    } // else if ...
    
  };

  // execute on load and on window resize
  $(window).resize(resizeActions);
  resizeActions();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="row">
    <div class="col-xs-12">
      <img class="img-responsive center-block" id="notice_banner" alt="" src="//placehold.it/200x200" />
    </div>
    <div class="col-xs-12">
      <p id="altText" style="display: none">
        This is a text!
      </p>
    </div>
  </div>

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

Experiencing difficulty with implementing an Angular filter to search through a list

Currently, I am utilizing an angular filter to search through a list. The searching functionality using the filter works as expected. However, I have encountered an issue with a checkbox labeled 'Select All'. When I search through the list and on ...

Mastering the jQuery animateNumber plugin: An in-depth guide to animating floating

When trying to animate a number, I encountered an issue with floats. Integers work fine, but floats seem to be causing problems. For example, if the propNumberGV is set to 5.5 and the new data.value is 10.0, the animation starts at 0.0 instead of 5.5. The ...

Creating a collapsing drop down menu with CSS

I utilized a code snippet that I found on the following website: Modifications were made to the code as shown below: <div class="col-md-12"> ... </div> However, after rearranging the form tag, the drop-down menu collapse ...

Converting an object with a combination of different index types into a string representation

I'm dealing with a unique object structure that behaves similarly to an array, except it contains a mix of index types (numbers and strings). Here's an example: var myObj = []; myObj[0] = 'a'; myObj[1] = 'b'; myObj[2] = &apos ...

Is there a way to store the URLs that a user visits locally with a Chrome extension using JavaScript?

I am working on a Chrome extension that will save the URL link of the active tab when a user clicks on the extension icon. The goal is to store this URL in local storage and keep it saved until the active window is closed. I have set up an array called tab ...

Struggling to integrate an audio player specifically for mp3 files and feeling quite perplexed by the process

I'm struggling with implementing an audio player for a file sharing platform, specifically only for .mp3 files. I have successfully implemented a function for images (.jpeg and others), but I am unsure how to do the same for mp3 files. function is_au ...

Transforming a high chart into an image and transmitting it to the server through an ajax request

I am looking for a way to save multiple charts as PDF files on the server using an AJAX call. Each chart is rendered in a distinct container on the same page, and I need to convert them into images before sending them to the server for export. Any assist ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Managing Asynchronous Operations in Vuex

Attempting to utilize Vue's Async Actions for an API call is causing a delay in data retrieval. When the action is called, the method proceeds without waiting for the data to return, resulting in undefined values for this.lapNumber on the initial call ...

Incorporate a Three.js viewer within a WPF application

I am currently exploring the use of Three.js to develop a versatile 3D renderer that can run seamlessly on various platforms through integration with a "WebView" or "WebBrowser" component within native applications. I have successfully implemented this sol ...

Is axios allowed to be used in this scenario?

As a newcomer to web development, I apologize in advance if my question seems basic or if the details provided are insufficient. Nevertheless, I hope you can assist me with the following query: Is it possible to execute an axios.post request within a vue. ...

searching for a refined method to tackle this challenge

I'm relatively new to Angular and I'm interested in finding a more efficient solution for this particular task. The code below functions correctly, but I am uncertain if it is the best approach to achieve the desired outcome. HTML <div ng-a ...

Loading drop-down menu content after making an AJAX request

I understand that AJAX functions asynchronously (hence the "A" in AJAX). I have placed all the code that relies on the result of the AJAX call inside the success callback function. However, even after making the call, the select dropdown box is not being p ...

The authentication callback function fails to execute within Auth0 Lock

I'm having an issue with logging into my application using Auth0. I have integrated Auth0 Lock version 10.3.0 through a CDN link in my project and am utilizing it as shown below: let options = { disableSignupAction: true, rememberLastLogin: f ...

What distinguishes {key:" "} from {key:" "}, when it comes to JSON files?

I have been working on implementing validation using express Router. The issue I encountered is that when I pass {title:""}, the express-validator does not throw an error. However, when I pass {title:" "}, it works properly. exports.postValidatorCheck = [ ...

Creating a REST API with the POST method using Vanilla JavaScript/AJAX and encountering a 400 error (Bad request) issue

Could you assist me in figuring out how to utilize the POST method in vanilla JavaScript (without jQuery)? I've been attempting to do so with this code: var call = { "filterParameters": { "id": 18855843, "isInStockOnly": false, "newsOn ...

Error in Continuous Integration for Angular 4: Unable to access property 'x' of an undefined variable

i am trying to display some data on the form but encountering an error: TypeError: Cannot read property 'title' of undefined below is my component code : book:Book; getBook(){ var id = this.route.snapshot.params['id']; ...

Challenges arising from the use of 'position: absolute' in managing relationships between grandparents, parents, and children

Within my React project, all code is enclosed within the root div (grandparent). In my Project.js component, there is a separate div (parent) solely responsible for the background color. This component is then displayed in App.js without any additional d ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

The load() function is experiencing issues with executing scripts

I have a script on the page where I want to load the file: <SCRIPT type="text/javascript"> $(function() { $("#storefront").click(function () { alert("POTANGINA"); $(".centerdiv").load("storefront_a.php"); ...