Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 22, 2024 . #HowTo . #Html

Write a jQuery Code to Fix broken images automatically

Broken images often result from failed loading. By checking the status of each image, we can dynamically replace broken ones.

To begin, we'll create a jQuery script that detects broken images on your webpage. This snippet checks for image errors and replaces the source with a fallback image if an error is found.

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
 <img src="/img.png"/>
 <script>
   $(document).ready(function() {
     $('img').on('error', function() {
       $(this).attr('src', 'https//app.3schools.in/logo.jpg'); // Replace with your fallback image
     });
   });
 </script>

Using the onerror Attribute

An alternative approach is to utilize the onerror attribute directly in HTML to handle broken images.

<img src="broken-image.jpg" onerror="this.src='https://app.3schools.in/logo.jpg';" alt="Image">

save
listen
AI Answer
Write Your Answer
loading
back
View All