HTML ondurationchange Attribute

Beginner
⏱️ 5 min read
📚 Updated: Jun 2026
🎯 3 Examples
Media & Playback

Introduction

The ondurationchange attribute is an inline event handler that runs JavaScript when the durationchange event fires. That happens on <audio> and <video> whenever element.duration changes. Before metadata loads, duration is NaN; once the browser knows the total length, duration becomes a number in seconds and durationchange fires. Use it to update progress bars, show total runtime, or react when a live stream length changes. It does not fire on every playback tick—use ontimeupdate for current position.

What You’ll Learn

01

Event handler

Inline JS.

02

durationchange

Media event.

03

audio / video

Media elements.

04

element.duration

NaN → seconds.

05

addEventListener

Preferred way.

06

.ondurationchange

Property API.

Purpose of ondurationchange Attribute

The primary purpose of ondurationchange is to react when the browser learns or updates the total length of media. You might format and display runtime (“3:42”), enable a seek bar, or log when a stream’s duration shifts. The event is part of the media loading lifecycle alongside loadedmetadata, loadeddata, and canplay.

Read element.duration inside the handler—it is in seconds. Before metadata arrives, duration is NaN. The old reference used alert() in demos—avoid that in real apps. Status text or UI updates are clearer.

💡
Prefer addEventListener on the media element

Production code should use video.addEventListener("durationchange", handler). Inline ondurationchange on <audio> or <video> works for learning but separates concerns less cleanly.

📝 Syntax

Set ondurationchange on audio or video, or assign element.ondurationchange:

ondurationchange.html
<script>

  function handleDurationChange(el) {

    var secs = Math.floor(el.duration);

    console.log("Duration: " + secs + " seconds");

  }

</script>



<audio controls ondurationchange="handleDurationChange(this)">

  <source src="song.mp3" type="audio/mpeg">

</audio>

Syntax Rules

  • Value is JavaScript code executed when the durationchange event fires.
  • Applies to <audio> and <video> media elements.
  • Fires when element.duration changes (including NaN → number).
  • JavaScript: media.ondurationchange = function() { … }.
  • Modern alternative: media.addEventListener("durationchange", handler).
  • May fire again if duration updates (e.g. live streams or source swap).

💎 Values

The ondurationchange attribute accepts a string of JavaScript code:

  • ondurationchange="handleDurationChange(this)" — Pass the element to a function.
  • ondurationchange="updateRuntime()" — Call a named function.
  • JavaScript: video.ondurationchange = () => { … } assigns the handler.
ondurationchange-js.html
const audio = document.getElementById("track");

audio.addEventListener("durationchange", () => {

  const secs = Math.floor(audio.duration);

  document.getElementById("runtime").textContent = secs + " seconds";

});

⚡ Quick Reference

EventWhen it firesHandler
durationchangeelement.duration changesondurationchange
loadedmetadataMetadata (incl. duration) readyonloadedmetadata
loadeddataFirst frame readyonloadeddata
canplayEnough data to startoncanplay
Before metadataduration is NaNWait for durationchange

Applicable Elements

TargetSupported?Notes
<audio>YesInline ondurationchange on audio
<video>YesMost common use
<source>NoEvent fires on parent media element
<input>, <img>NoNot media duration events

ondurationchange vs onloadedmetadata vs onloadeddata vs oncanplay

HandlerWhen it firesTypical use
onloadedmetadataMetadata parsed (duration often known)Read duration, dimensions, tracks
ondurationchangeWhenever duration changesUpdate total runtime UI
onloadeddataFirst frame of media availableShow poster / first frame
oncanplayEnough buffered to startEnable play button, hide loader

Examples Gallery

Inline ondurationchange on audio, dynamic property assignment, and durationchange vs loadedmetadata.

👀 Live Preview

Load the audio — when duration becomes known, status updates:

Duration: unknown (NaN until metadata loads)…

Example — Inline ondurationchange on audio

Read element.duration when metadata arrives:

inline-ondurationchange.html
<audio controls ondurationchange="handleDurationChange(this)">

  <source src="song.mp3" type="audio/mpeg">

</audio>



<script>

  function handleDurationChange(el) {

    var secs = Math.floor(el.duration);

    console.log("Duration: " + secs + " seconds");

  }

</script>
Try It Yourself

How It Works

The browser fires durationchange on the audio element when total length becomes known. Pass this to read duration inside the handler.

Dynamic Values with JavaScript

Assign element.ondurationchange after the element exists:

dynamic-ondurationchange.html
<script>

  var video = document.getElementById("clip");

  video.ondurationchange = function () {

    var secs = Math.floor(video.duration);

    console.log("Duration: " + secs + " seconds");

  };



  // Or addEventListener form:

  video.addEventListener("durationchange", function () { /* … */ });

</script>
Try It Yourself

How It Works

Register the handler once at page load. When metadata arrives, durationchange runs and video.duration holds the total length in seconds.

Example — durationchange vs loadedmetadata

See where durationchange fits and watch duration go from NaN to a known value:

duration-compare.html
console.log(audio.duration); // NaN before metadata

audio.addEventListener("loadedmetadata", () => { /* metadata ready */ });

audio.addEventListener("durationchange", () => {

  console.log(Math.floor(audio.duration) + " seconds");

});
Try It Yourself

How It Works

durationchange tracks changes to element.duration, not playback position. For current time during playback, listen for timeupdate.

♿ Accessibility

  • Expose total duration in UI — Screen reader users benefit when runtime is visible and announced (e.g. “3 minutes 42 seconds”).
  • Do not rely on duration alone for controls — Provide native controls or fully accessible custom players with keyboard support.
  • Avoid alert() on durationchange — Update visible status or progress labels instead of blocking dialogs.
  • Handle unknown duration gracefully — Show “Live” or “Loading…” while duration is NaN.
  • Captions and transcripts — Media events do not replace accessible alternatives for audio and video content.

🧠 How ondurationchange Works

1

Media starts loading

Browser fetches the file.

loadstart
2

duration is NaN

Total length not known yet.

NaN
3

durationchange fires

Metadata parsed; seconds known.

ondurationchange
=

Update runtime UI

Show total length.

Browser Support

The durationchange event and ondurationchange handler are supported in all modern browsers on <audio> and <video> elements — Chrome, Firefox, Safari, and Edge.

DOM Events · Fully supported

Universal ondurationchange support

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

99% 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
ondurationchange attribute 99% supported

Bottom line: Universal support on media elements. Test with slow network throttling to see duration stay NaN longer before metadata arrives.

💡 Best Practices

✅ Do

  • Use addEventListener on the media element — Clearer than inline ondurationchange.
  • Check for NaN before formatting — Guard UI until durationchange fires.
  • Format duration for humans — Convert seconds to mm:ss for display; use Math.floor in simple demos.
  • Handle live streams — Duration may change again; keep listening for updates.
  • Provide fallbacks — Include text inside audio/video for unsupported browsers.

❌ Don’t

  • Do not confuse with timeupdate — durationchange = total length; timeupdate = current position.

Conclusion

The ondurationchange attribute runs JavaScript when element.duration changes on audio or video. Use it to show total runtime, enable seek UI, or react when a stream length updates.

Prefer addEventListener("durationchange", …), handle NaN before metadata loads, and pair with onloadedmetadata or oncanplay when you need broader load-state signals.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about ondurationchange

Bookmark these before wiring your next event handler.

5
Core concepts
🌐 02

audio / video

Media only.

Scope
🔄 03

NaN → seconds

Read duration.

Pattern
📝 04

addEventListener

Preferred.

Modern
05

Not timeupdate

Total length only.

Note

❓ Frequently Asked Questions

It runs JavaScript when the durationchange event fires — when element.duration changes on audio or video.
audio and video elements. The event fires on the media element loading the resource.
loadedmetadata fires when metadata is first available. durationchange fires whenever duration changes — including NaN to seconds or live stream updates.
Until metadata is parsed, total length is unknown. After metadata loads, duration becomes a number in seconds.
Prefer media.addEventListener("durationchange", …). Inline ondurationchange works for simple demos.
Yes. It fires on any duration change — first metadata, source swaps, or live stream length updates.

Handle media duration changes

Practice inline ondurationchange, dynamic assignment, and durationchange vs loadedmetadata in the Try It editor.

Try ondurationchange 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