top | item 31177503

(no title)

sir_pepe | 3 years ago

The real fun comes when you consider the interactions between setting an event HTML attribute and the DOM property. If memory serves, setting the DOM property for eg. "onclick" to some JS function overrides (but does not change) the HTML attribute "onclick", while setting the HTML attribute replaces an existing property value. Took me quite some time to reverse-engineer this behavior for use in custom elements. Check out this library if you want/need html event attibutes for custom events on your web components: https://github.com/SirPepe/OnEventMixin

Oh, any by the way, HTML attributes work with event bubbling. Add "onsubmit" to some div tag and it will catch submit events originating from any of the div's children. This is why there is support for eg. "onlick" on stuff like h1.

discuss

order

lifeplusplus|3 years ago

what's a difference between override vs replace, aren't both leading to the same outcome?

sir_pepe|3 years ago

Not quite! If you have an attribute "onclick" and set the DOM property "onclick", the attribute value stays unchanged, but if you click, the function set by the property gets called. Set the attribute an both the attribute value and the DOM property change - the latter to a function as described in the original article.

Think of the actual function that gets called as residing in an internal slot on the element. Both the attribute and the property can set the slot's value, and setting and the DOM propertie's getter accesses the slot directly. Sort of, if i remember correctly.