How7o
  • Home
  • Marketing
    MarketingShow More
  • OS
    OSShow More
    How to force quit frozen apps in Ubuntu
    Force Close an App in Ubuntu (xkill, System Monitor, kill -9)
    4 Min Read
  • Features
    FeaturesShow More
  • Guide
    GuideShow More
  • Contact
  • Blog
Reading: Replace Broken Images Automatically with JavaScript (and jQuery)
Share
Subscribe Now
How7oHow7o
Font ResizerAa
  • Marketing
  • OS
  • Features
  • Guide
  • Complaint
  • Advertise
Search
  • Categories
    • Marketing
    • OS
    • Features
    • Guide
    • Lifestyle
    • Wellness
    • Healthy
    • Nutrition
  • More Foxiz
    • Blog Index
    • Complaint
    • Sitemap
    • Advertise
Follow US
Copyright © 2014-2023 Ruby Theme Ltd. All Rights Reserved.
How7o > Blog > Web Development > Replace Broken Images Automatically with JavaScript (and jQuery)
Web Development

Replace Broken Images Automatically with JavaScript (and jQuery)

how7o
By how7o
Last updated: January 23, 2026
5 Min Read
Replace Broken Images Automatically with JavaScript
SHARE

I run a wallpaper-style site, which means I’m dealing with a lot of images—some from uploads, some from remote sources. And sooner or later, it always happens: an image gets removed, permissions change, a hotlink breaks, or the server starts returning “Access Denied”.

Contents
  • Best quick fix (inline): use the image onerror attribute
  • Cleaner inline version: call a function instead
  • Best scalable fix: handle ALL broken images with JavaScript (no HTML edits)
  • jQuery solution (simple and popular)
  • Extra tips (these made my gallery look cleaner)
  • Optional CSS (make fallback images look nice)
  • Final thoughts

When that happens, browsers show the ugly broken-image icon, and it completely ruins a grid layout. Worse: if your cards depend on consistent heights, broken images can make the whole page look “broken”. So I wanted a simple fix: if an image fails to load, automatically replace it with a default “not found” image.

Below are the cleanest solutions I’ve used in production—starting from the simplest inline method, then moving to a scalable JavaScript/jQuery approach that requires zero HTML editing.

Best quick fix (inline): use the image onerror attribute

If you control the HTML output (templates, CMS, etc.), the fastest solution is using onerror directly on the <img> tag.

<img src="image.png"
     alt="Wallpaper"
     onerror="this.onerror=null;this.src='/images/not-found.gif';">

Why the this.onerror=null part? Because if your fallback image also fails (wrong path, permission issue), you can end up in an infinite loop. This line prevents that.

Cleaner inline version: call a function instead

If you prefer not to keep logic inside HTML attributes, attach a function and reuse it:

<script>
function processError(img) {
  img.onerror = null;              // prevent infinite loop
  img.src = "/images/noimage.gif"; // fallback
  img.alt = "Image not found";
  return true;
}
</script>

<img src="image.png" alt="Wallpaper" onerror="processError(this);">

Best scalable fix: handle ALL broken images with JavaScript (no HTML edits)

This is what I use when pages have lots of images (galleries, infinite scroll, user uploads). You add one script and it automatically fixes broken images site-wide.

<script>
(function () {
  const FALLBACK_SRC = "/images/noimage.gif";

  function replaceWithFallback(img) {
    // Avoid looping if the fallback fails
    if (img.dataset.fallbackApplied) return;
    img.dataset.fallbackApplied = "1";
    img.src = FALLBACK_SRC;
    img.alt = img.alt || "Image not found";
    img.classList.add("img-fallback"); // optional: style it
  }

  // 1) Handle existing images
  document.querySelectorAll("img").forEach(img => {
    img.addEventListener("error", () => replaceWithFallback(img), { once: true });
  });

  // 2) Handle images added later (AJAX / infinite scroll)
  const observer = new MutationObserver(mutations => {
    for (const m of mutations) {
      m.addedNodes.forEach(node => {
        if (node.nodeType !== 1) return;
        if (node.tagName === "IMG") {
          node.addEventListener("error", () => replaceWithFallback(node), { once: true });
        } else {
          node.querySelectorAll?.("img").forEach(img => {
            img.addEventListener("error", () => replaceWithFallback(img), { once: true });
          });
        }
      });
    }
  });

  observer.observe(document.documentElement, { childList: true, subtree: true });
})();
</script>

This version also covers images injected after page load (common on wallpaper sites). That was a big deal for me, because my broken images weren’t only on the initial HTML—some came from “Load More” results.

jQuery solution (simple and popular)

If your site already uses jQuery, this is the classic approach:

<script>
$("img").on("error", function () {
  // Prevent infinite loop
  if ($(this).data("fallbackApplied")) return;
  $(this).data("fallbackApplied", true);

  $(this).attr("src", "/images/noimage.gif");
  $(this).attr("alt", $(this).attr("alt") || "Image not found");
});
</script>

Important: If you load images dynamically, you’ll need to attach the handler for newly added images too. The MutationObserver approach above is more future-proof.

Extra tips (these made my gallery look cleaner)

  • Use a fallback image with the same aspect ratio as your thumbnails (so it doesn’t stretch your layout).
  • Add a CSS style for fallbacks to make them look intentional (example: blur background, show “Not Found” text, etc.).
  • Fix the root cause too: if images are frequently “Access Denied”, check hotlink protection, CORS, token expiry, or storage permissions.

Optional CSS (make fallback images look nice)

img.img-fallback {
  object-fit: cover;
  filter: grayscale(1);
  opacity: 0.85;
}

Final thoughts

For small sites, the inline onerror trick is enough. But for image-heavy websites (like wallpaper galleries), a global JavaScript handler is the easiest way to keep the design clean. The moment an image fails, it gets replaced—no broken icons, no ugly layout jumps.

TAGGED:frontendimagesJavaScriptjQueryonerrorperformancetroubleshootingUX

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Next Article Configure Nginx for WordPress in aaPanel (fix 404 permalinks) Configure Nginx for WordPress in aaPanel (Fix Permalink 404 Errors)
Leave a Comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

FacebookLike
XFollow
PinterestPin
InstagramFollow

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!
Most Popular
CyberPanel too many redirects Laravel error fixed by restarting LiteSpeed
Fix CyberPanel Too Many Redirects (ERR_TOO_MANY_REDIRECTS) for Laravel Subdomain
January 23, 2026
How I Fixed Composer Dependency Errors
How I Fixed Composer Dependency Errors Using the –ignore-platform-reqs Flag (Step-by-Step Guide)
January 12, 2026
Transfer Discourse to a new server
How to Transfer Discourse to a New Server on AlmaLinux (Backup + Restore, Step-by-Step)
January 12, 2026
Installed Discourse on AlmaLinux
How I Installed Discourse on AlmaLinux (Docker Method, Step-by-Step)
January 12, 2026
Installing Docker on AlmaLinux guide
Install Docker on AlmaLinux: Step-by-Step (Docker CE + Compose)
January 12, 2026

You Might Also Like

Laravel Blade Time Format (HH:MM)
Web Development

How to Show Only Hours and Minutes in Laravel Blade (HH:MM)

3 Min Read
Return or throw an error in Laravel (JSON response vs exception)
Web Development

How to Manually Return or Throw an Error Exception in Laravel

6 Min Read
Send a simple email in Laravel using Mail::raw and SMTP
Web Development

How to Send a Simple Email in Laravel (Fast SMTP + Mail::raw)

4 Min Read
WooCommerce homepage filter to hide out of stock products
Web Development

Hide Out of Stock Products from Homepage in WooCommerce (Keep Them Visible Elsewhere)

5 Min Read

Always Stay Up to Date

Subscribe to our newsletter to get our newest articles instantly!
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Latest News

  • SEO Audit Tool
  • Client ReferralsNew
  • Execution of SEO
  • Reporting Tool

Resouce

  • Google Search Console
  • Google Keyword Planner
  • Google OptimiseHot
  • SEO Spider

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?