caramba
caramba

Reputation: 22490

jQuery data() listen when it gets changed

Is it possible (if yes how) to check, detect, listen or watch if

$('body').data('myValue',false) 

changes to true?

Of course I change it somewhere to true. The clue is I change it when an animation finishes and need to check somewhere else if it is finished. So when it changed the value I have to do something..

Upvotes: 1

Views: 695

Answers (2)

Vlad Cazacu
Vlad Cazacu

Reputation: 1540

There a few ways to do this:

  1. Use setInterval to check for changes in the element's attributes
  2. Use this plugin: http://meetselva.github.io/attrchange/. I haven't used this, so i can't say if it works well
  3. Use the DOMAttrModified DOM event. IE's equivalent is propertychange. This doesn't have great browser support, so it would be a good idea to add a fallback with setInterval.
  4. As T.J. Crowder suggested, trigger an event when changing the data attribute

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075189

Of course I change it somewhere to true. The clue is I change it when an animation finishes and need to check somewhere else if it is finished.

This is where custom events can be handy. In the place where you change it:

$('body').data('myValue', true).trigger('datachanged');

and where you need to know:

$('body').on('datachanged', function() {
    // Use the updated information
});

For more about custom events, search for "custom" on the on API doc page and the trigger API doc page.

Upvotes: 6

Related Questions