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