Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting attribute change of value of an attribute I made

Tags:

html

jquery

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!"); }); 
like image 866
Majo0od Avatar asked May 27 '13 23:05

Majo0od


People also ask

What type of method should be used to change the value of an attribute?

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.

How do you get the value of a data attribute?

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.


1 Answers

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);   }); }); 
like image 110
martineno Avatar answered Oct 03 '22 08:10

martineno