I’m trying to use onerror with source tag but the function isn’t being called.

                <source srcset="<?=home(1).str_replace(array('.jpg', '.png', '.gif'),".webp",$movie->thumb3) ?>" type="image/webp" onerror="fallback()">
                <source srcset="<?=home().$movie->thumb3 ?>" type="image/jpeg">
                <img src="<?=home().$movie->thumb3 ?>" alt="<?=$movie_title?>">


function fallback() {
      var src = $(this).attr("srcset");
        src = src.replace("https://webp","https://images");

The fallback image isn’t being used? How do i solve?


That’s because $(this) is returning the window object rather than the video element. You also wouldn’t need jQuery for it.

You should target the event with onerror. This gives you the correct object for which you would like to change the src instead.


  <img srcset="https://www.example.com/200/300" onerror="fallback(this)" />
function fallback(image) {
  /* prevent endless loop */
  image.onerror = null;
  /* an error occured, change the source */
  var src = image.srcset;
  var newSrc = src.replace("https://www.example","https://www.fillmurray");
  image.srcset = newSrc;


Although w3c still lists the onerror event as usable, onerror is not recommended by mozilla and has some browser compatibility issues.

Another reason it’s not advised to use anymore: It turns out that in a webpage where users are able to post (or otherwise add) their own content the onerror event can be used in a very exploitative way to hijack the webpage.


One alternative to using onerror is to manually check if it exists and if not provide an alternative path: Check if image exists on server using JavaScript?