HTML onabort Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onabort attribute is an inline event handler that runs JavaScript when a media resource stops loading before it finishes. It applies to elements like <img>, <audio>, <video>, and <track>. The abort event fires when loading is canceled—for example when script clears src, assigns a new URL mid-load, or the user navigates away. It is not the same as a failed load: a broken image URL triggers onerror, not onabort.

What You’ll Learn

01

Event handler

Inline JS.

02

Media elements

img audio video.

03

Load canceled

Not failed.

04

vs onerror

Abort vs fail.

05

addEventListener

Preferred way.

06

.onabort JS

Property API.

Purpose of onabort Attribute

The primary purpose of onabort is to respond when a media download is interrupted before completion. Single-page apps that swap image galleries may cancel in-flight requests. Lazy-loading libraries might abort loads for off-screen images. You can log canceled requests, release memory, or show a placeholder when a load does not finish.

The old reference incorrectly suggested that a missing image or “failed to load” triggers onabort. That is onerror. onabort means the browser stopped an in-progress fetch—not that the server returned 404 or the format was invalid.

💡
Prefer addEventListener

Inline onabort="…" works for tutorials, but production code should use element.addEventListener("abort", handler) to separate HTML from JavaScript.

📝 Syntax

Set onabort to a JavaScript statement or function call on a media element:

onabort.html
<img

  src="photo.jpg"

  alt="Profile photo"

  onabort="handleAbort()">



<video src="clip.mp4" onabort="logCanceled()"></video>



<script>

  function handleAbort() {

    console.log("Image load was canceled.");

  }

</script>

Syntax Rules

  • Value is JavaScript code executed when the abort event fires.
  • Applies to <img>, <audio>, <video>, and <track>.
  • Fires only when loading is canceled mid-request, not on successful load or error.
  • JavaScript property: element.onabort = function() { … }.
  • Modern alternative: element.addEventListener("abort", handler).
  • Do not confuse with AbortController fetch API—related concept, different API.

💎 Values

The onabort attribute accepts a string of JavaScript code:

  • onabort="handleAbort()" — Call a named function.
  • onabort="console.log('canceled')" — Inline statement.
  • onabort="this.alt='Load canceled'" — Use this for the element.
  • JavaScript: img.onabort = function (e) { … } assigns the same handler.
onabort-js.html
const img = document.getElementById("photo");

img.addEventListener("abort", () => {

  console.log("Load canceled");

});

// Cancel in-progress load
img.src = "";

⚡ Quick Reference

EventWhen it firesHandler
abortLoad canceled before finishonabort / addEventListener
errorLoad failed (404, network)onerror
loadLoad completed successfullyonload
Cancel via JSimg.src = "" mid-loadMay trigger abort
Broken URLFile not foundTriggers error, not abort

Applicable Elements

ElementSupported?Notes
<img>YesMost common use
<video>, <audio>YesMedia resource loading
<track>YesSubtitle/track file load
<form>, <a>NoDifferent event model

onabort vs onerror vs onload

HandlerTypical causeExample
onabortLoad stopped before doneScript clears src
onerrorResource could not load404, corrupt file
onloadResource loaded OKImage displayed

Examples Gallery

Inline onabort handler, addEventListener, and abort vs error comparison.

👀 Live Preview

Start loading an image, then cancel it to trigger abort:

Abort demo

Waiting…

Example — Inline onabort Handler

Call a function when loading is aborted:

inline-onabort.html
<img

  src="photo.jpg"

  alt="Example"

  onabort="handleImageAbort()">



<script>

  function handleImageAbort() {

    console.log("Image loading was canceled.");

  }

</script>
Try It Yourself

How It Works

When the browser aborts fetching the image resource, it runs the JavaScript in onabort. The handler runs once per canceled load attempt.

Dynamic Values with JavaScript

Attach the handler with addEventListener or onabort property:

dynamic-onabort.html
<img id="dynamicImage" alt="Dynamic">



<script>

  const img = document.getElementById("dynamicImage");

  img.addEventListener("abort", () => {

    alert("Image loading aborted!");

  });

  img.src = "photo.jpg";

  img.src = ""; // cancel mid-load

</script>
Try It Yourself

How It Works

Assign the handler before or during loading. Clearing src or changing it while a fetch is active can fire abort on the previous request.

Example — onabort vs onerror

Do not use a broken URL to demo onabort—that fires error:

abort-vs-error.html
<!-- Cancel load → abort -->

img.addEventListener("abort", () => log("canceled"));

img.src = "photo.jpg";

img.src = "";



<!-- Bad URL → error -->

img.addEventListener("error", () => log("failed"));

img.src = "missing.jpg";
Try It Yourself

How It Works

abort, error, and load are separate events on media elements. Pick the handler that matches the situation you need to handle.

♿ Accessibility

  • Provide alt text — On <img>, always set meaningful alt; abort handlers often swap to fallback content that must stay accessible.
  • Announce load failures — If abort means content is unavailable, inform users visually and with ARIA live regions where appropriate.
  • Do not rely on alerts — Replace alert() in demos with inline status messages in real apps.
  • Video/audio captions — If track loading aborts, ensure captions still work or show a clear message.
  • Keyboard users — Cancel actions triggered by buttons should be focusable and labeled.

🧠 How onabort Works

1

Load starts

Browser fetches img/video src.

Request
2

Load canceled

src cleared or changed mid-fetch.

Abort
3

Handler runs

onabort or listener executes.

JS
=

Cleanup / UX

Log, placeholder, retry UI.

Browser Support

The abort event and onabort handler are supported in all modern browsers on <img>, <audio>, <video>, and <track>. Exact timing of when abort fires may vary slightly if the resource loads from cache instantly.

DOM Events · Fully supported

Universal onabort support

All major browsers fire the underlying event and honor the onabort handler attribute.

98% Browser support
Google Chrome Fully supported
Full support
Mozilla Firefox Fully supported
Full support
Apple Safari Fully supported
Full support
Microsoft Edge Fully supported
Full support
Internet Explorer IE 9+ supported
Full support
Opera Fully supported
Full support
onabort attribute 98% supported

Bottom line: Use addEventListener("abort", …) in modern apps; test cancel behavior with slow or uncached resources.

💡 Best Practices

✅ Do

  • Use addEventListener — Prefer it over inline onabort in production code.
  • Handle error separately — Use onerror for failed loads, onabort for canceled loads.
  • Provide fallback UI — Show placeholder or retry when loads are canceled intentionally.
  • Test real cancel paths — Simulate mid-load src changes, not 404 URLs.

❌ Don’t

  • Avoid alert() — Use status text or toast notifications instead.
  • Do not block navigation — Keep abort handlers lightweight.

Conclusion

The onabort attribute runs JavaScript when media loading is canceled before it completes. It applies to img, audio, video, and track elements.

Understand the difference from onerror, prefer addEventListener("abort", …), and use abort handlers to clean up or improve UX when loads are intentionally stopped.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onabort

Bookmark these before wiring your next event handler.

5
Core concepts
📷 02

Media elements

img video audio.

Scope
🚫 03

vs onerror

404 = error.

Compare
📝 04

addEventListener

Preferred.

Modern
⚙️ 05

Clear src

Triggers abort.

Pattern

❓ Frequently Asked Questions

It runs JavaScript when a media element’s resource load is aborted before completion.
<img>, <audio>, <video>, and <track>.
No. A missing or invalid URL triggers onerror. onabort is for canceled in-progress loads.
Use addEventListener("abort", handler) in modern code. Inline onabort is fine for learning and small demos.
Set element.src = "", remove src, or assign a new URL while the previous load is still in progress.
img.onabort = function() { … } or img.addEventListener("abort", handler).

Handle canceled media loads

Practice inline onabort, addEventListener, and abort vs error in the Try It editor.

Try onabort demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful