I created an attribute in HTML data-select-content-val
and it is stuffed with information dynamically.
Is there a way to detect when the attribute's value has changed?
$(document).on("change", "div[data-select-content-val]", function(){ alert("BOOP!"); });
In order to set an attribute on a specific element, we use the setAttribute() method. It updates the value of an attribute existing on an element or sets a new attribute with a new name and value on an element if one does not exist.
To get a data attribute through the dataset object, get the property by the part of the attribute name after data- (note that dashes are converted to camelCase). Each property is a string and can be read and written.
You would have to watch the DOM node changes. There is an API called MutationObserver
, but it looks like the support for it is very limited. This SO answer has a link to the status of the API, but it seems like there is no support for it in IE or Opera so far.
One way you could get around this problem is to have the part of the code that modifies the data-select-content-val
attribute dispatch an event that you can listen to.
For example, see: http://jsbin.com/arucuc/3/edit on how to tie it together.
The code here is
$(function() { // Here you register for the event and do whatever you need to do. $(document).on('data-attribute-changed', function() { var data = $('#contains-data').data('mydata'); alert('Data changed to: ' + data); }); $('#button').click(function() { $('#contains-data').data('mydata', 'foo'); // Whenever you change the attribute you will user the .trigger // method. The name of the event is arbitrary $(document).trigger('data-attribute-changed'); }); $('#getbutton').click(function() { var data = $('#contains-data').data('mydata'); alert('Data is: ' + data); }); });
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