Reputation: 916
I am trying to add an event listener to detect a change in the state of an HTML5 details node.
Initially I tried attaching a listener to the open and close events as it makes logical sense to me for a details node to have those listeners, but it doesn't and I do not see any mention of them in the html5 spec.
I tried (in Google Chrome) the change event, since the html5 spec (and Inspect Element confirms) that the way to open and close details is to add/remove the open attribute. I was hoping that the node gaining/losing an attribute would trigger the change event, but apparently it does not.
How the hell do I trigger a script action off of the changing of state of a details node?
Upvotes: 2
Views: 1350
Reputation: 353
Listening to DOMAttrModified works for many browsers, and DOMSubtreeModified works for Chromium based browsers, but nowadays there's a more specific event available to listen for on details nodes:
You can add a listener/handle the toggle event for the details
node when you want to detect the details
node is opened or closed.
So the opening or closing of the details' node contents cannot be cancelled.
This example selects the first details
node it can find in a document. Think about some other query selector, or document.querySelectorAll('details')
or even some js framework to set the event on multiple details
nodes (i.e. $('details').on('toggle', <function here>)
.
document.querySelector('details').addEventListener('toggle',
function afterToggle(e) {
if(e.target.open){
//do something when opened
}
else {
//do something when closed
}
}
);
Upvotes: 0