I have data-segment attribute in my body tag that is changed by a slider. I need to trigger a function based on the value of this, when it is changed.
I'm not sure how to attach an event listener in this case though?
`There is no reliable cross-browser way to receive an event when a DOM node attribute is changed. Some browsers support "DOM mutation events", but you shouldn't rely on them, and you may Google that phrase to learn about the ill-fated history of that technology.
If the slider control does not fire a custom event (I would think most modern ones do), then your best bet is to set up a setInterval()
method to poll the value.
You can use MutationObserver
, which is an API available in every browser and avoid polling with setInterval
. If you have a reference to your element in element
, you could do this:
const mutationObserver = new MutationObserver(callback);
mutationObserver.observe(element, { attributes: true });
function callback() {
// This function will be called every time attributes are
// changed, including `data-` attributes.
}
Other changes in your element can be easily detected with this API, and you can even get the old and new values of the property that changes in your callback tweaking the configuration object in the call to observe
. All the documentation about this can be read in MDN: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserverInit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With