Reputation: 185
I want to take 'data-defaulting' from '.check-img' if its 'src' returns an error, and then assign the value to its sibling source's src.
The idea is to check for the mobile version image available or not and if not, take the default value and display the default image in mobile by assigning that as srcset to mobile source.
This seems to be not working, and the request for the image which is not present is repeatedly happening.
<picture>
<!-- Mobile image -->
<source srcset="data-defaultimg value should be here if .check-img (mobile image src) returns error" media="(max-width:768px)">
<!-- Virtual image with desktop image as data-defaultImage value -->
<img style="display: none" src="mobile image src here" alt="" class="check-img" data-defaultimg="default src here">
<!-- Desktop image. -->
<img src="desktop-img-src" alt="" class="img-fluid">
</picture>
jQuery for checking the error and assigning "defaultimg" value to mobile image srcset.
$("picture img.check-img").each(function(){
$(this).on('error', function(){
$(this).siblings("source").attr("srcset", $(this).data('defaultimg'));
})
});
I am not sure why the missing image request keeps on going. Please help. Thanks.
Upvotes: 1
Views: 48
Reputation: 4335
To avoid loading the not found image repeatedly, just remove the error event after the error is processed.
$("picture img.check-img").each(function() {
$(this).on('error', function() {
$(this).off('error');
$(this).siblings("source").attr("srcset", $(this).data('defaultimg'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<picture>
<!-- Mobile image -->
<source srcset="" media="(max-width:768px)">
<!-- Virtual image with desktop image as data-defaultImage value -->
<img style="display: none" src="does/not/exist.jpg" alt="" class="check-img" data-defaultimg="https://pbs.twimg.com/profile_images/420241225283674113/xoCDeFzV_400x400.jpeg">
<!-- Desktop image. -->
<img src="desktop-img-src" alt="" class="img-fluid">
</picture>
Upvotes: 1