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!"); });
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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); }); });
Method 2
You can use MutationObserver to track attribute changes including data-*
changes. For example:
var foo = document.getElementById('foo');
var observer = new MutationObserver(function(mutations) {
console.log('data-select-content-val changed');
});
observer.observe(foo, {
attributes: true,
attributeFilter: ['data-select-content-val'] });
foo.dataset.selectContentVal = 1;
<div id='foo'></div>
Method 3
There is this extensions that adds an event listener to attribute changes.
Usage:
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> <script type="text/javascript" src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>
Bind attrchange handler function to selected elements
$(selector).attrchange({ trackValues: true, /* Default to false, if set to true the event object is updated with old and new value.*/ callback: function (event) { //event - event object //event.attributeName - Name of the attribute modified //event.oldValue - Previous value of the modified attribute //event.newValue - New value of the modified attribute //Triggered when the selected elements attribute is added/updated/removed } });
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0