Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monitor when the body 'data' attribute changes in jQuery?

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?

like image 315
S16 Avatar asked Oct 08 '22 12:10

S16


2 Answers

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

like image 123
Kenan Banks Avatar answered Oct 10 '22 08:10

Kenan Banks


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

like image 41
adlr0 Avatar answered Oct 10 '22 09:10

adlr0