html icon indicating copy to clipboard operation
html copied to clipboard

Add a Generic "onrender" or "onattach" Event for HTML Elements

Open anotherCoward opened this issue 1 year ago • 3 comments

What problem are you trying to solve?

Currently, there is no native way in HTML to detect when a generic container element (such as <div>, <section>, etc.) has been rendered and attached to the DOM, and its layout has been calculated.

This limitation makes it difficult to implement UI patterns that require knowledge of the element’s rendered size or need to trigger logic immediately after the element is available in the DOM (e.g., for dynamic transitions, collapsible panels, or responsive layouts).

What solutions exist today?

Developers are forced to use workarounds such as:

  • Using <img src="404" onerror="..."> to trigger logic after rendering (hacky and not semantic)
  • Relying on JavaScript frameworks or MutationObservers (adds complexity and overhead)
  • Setting arbitrary large values for CSS properties like max-height (not robust or accessible)
  • Using global scripts to loop through all matching elements after page load (inefficient for dynamic content)

How would you solve it?

A generic event for HTML elements, such as onrender or onattach, which fires when:

  • The element is attached to the DOM
  • Its layout and dimensions are available (i.e., after rendering and style calculation)

This event would allow developers to run logic (e.g., set dynamic styles, initialize transitions, measure content) in a reliable and declarative way, without hacks or global scripts.

Anything else?

Example:

<div onrender="initCollapse(this)">
  <!-- content -->
</div>

Or as an event listener:

element.addEventListener('render', function(e) {
  // Element is now in the DOM and layout is available
});

Benefits

  • Enables robust UI patterns for dynamic content and transitions
  • Reduces reliance on hacks and global scripts
  • Improves accessibility and maintainability
  • Makes it more declarative and developer-friendly

Use Cases

  • Collapsible panels with animated transitions based on content height
  • Responsive components that need to measure their own size
  • Widgets that initialize only after being attached to the DOM
  • Any scenario where layout-dependent logic is needed immediately after rendering

References

anotherCoward avatar Sep 01 '25 11:09 anotherCoward

Regarding onrender it sounds like you're after the ResizeObserver API. While it doesn't really fire every time the style is recalculated, it does once per rendering frame, after the browser did its auto-recalc, which seems a lot more appropriate for your use case.

Kaiido avatar Sep 01 '25 12:09 Kaiido

@Kaiido sadly no. The ResizeObserver API is designed to find multiple Elements or requires a bigger script block with an explicit reference (like an ID or class) to the element. It doesn't refer directly to the element, that was attached.

Here is an example with a low-code work-around, where I wanted to use a simple CSS Animation to not show the full text instantly:

<div class="collapsible-container">
    <div style="font-weight: bold;" role="collapse-label"></div>
    <a href="#" role="collapse-button" onclick="this.nextElementSibling.style.display == 'block' ? (this.nextElementSibling.style.display = 'none', this.innerHTML='Expand') : (this.nextElementSibling.style.display = 'block', this.innerHTML='Collapse');" style="margin-bottom: 0.5em;">Collapse</a>
    <div role="collapse-content" style="display: block;">
        <p>
          Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
          sed diam nonumy eirmod tempor invidunt ut labore et dolore
          magna aliquyam erat, sed diam voluptua.
        </p>
        <p>
          At vero eos et accusam et justo duo dolores et ea rebum.
          Stet clita kasd gubergren, no sea takimata sanctus est
          Lorem ipsum dolor sit amet.
        </p>
    </div>
    <img onerror="this.previousElementSibling.style.maxHeight = this.previousElementSibling.offsetHeight+'px'" src="404" style="display: none;">
</div>

anotherCoward avatar Sep 01 '25 13:09 anotherCoward

Update: Custom Elements Parity Approach

After thinking about @Kaiido's feedback and researching existing patterns, I realized there's already precedent for this in Custom Elements:

Custom Elements already have this:

connectedCallback() { /* element connected to DOM */ }
disconnectedCallback() { /* element removed from DOM */ }

It would extend these lifecycle events to ALL HTML elements, not just Custom Elements.

Benefits:

  • Leverages existing browser infrastructure
  • Solves the "element connected + layout available" problem
  • Makes lifecycle events a universal HTML feature, not just a Custom Elements privilege

Suggested Implementation:

  • onconnected / ondisconnected attributes for all elements
  • connected / disconnected events for addEventListener
  • Developer can combine with requestAnimationFrame() for layout timing

Example:

// as event listener
element.addEventListener('connected', function() {
  requestAnimationFrame(() => {
    console.log(element.offsetHeight, element.offsetWidth);
    initCollapse(element);
  });
});

// as HTML Attribute
<div onconnected="requestAnimationFrame(() => initCollapse(this))">

anotherCoward avatar Oct 15 '25 08:10 anotherCoward