Javascript: Listen for Attribute Change

JavaScript: Listen for attribute change?

You need MutationObserver, Here in snippet I have used setTimeout to simulate modifying attribute

var element = document.querySelector('#test');
setTimeout(function() {
element.setAttribute('data-text', 'whatever');
}, 5000)

var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === "attributes") {
console.log("attributes changed");

// Example of accessing the element for which
// event was triggered
mutation.target.textContent = "Attribute of the element changed";
}

console.log(mutation.target);
});
});

observer.observe(element, {
attributes: true //configure it to listen to attribute changes
});
<div id="test">Dummy Text</div>

Firing event on DOM attribute change

Note: As of 2012, Mutation Events have been removed from the standard and are now deprecated. See other answers or documentation for how to use their replacement, MutationObserver.

You are referring to DOM Mutation Events. There is poor (but improving) browser support for these events. Mutation Events plugin for jQuery might get you some of the way.

JQuery how to listen for a element attribute/property change event

For reference, PrettyinPink's Comment was what was needed; looking up Mutation Observer rather than the older and more prolific Mutation Event was what was needed:

// Here we watch for new elements
const observer = new MutationObserver(function () {
console.log('observed!');
if($('#subBut').prop('disabled')) {
$('#reasons').slideDown();
}
else {
$('#reasons').slideUp();
}
});

// Param 1 of observe() must be a Node - document is a valid Node,
// but not advisable, limit the watcher to as small a context as possible
// Important here to set attributes to be true to check these.
observer.observe(document.getElementById('subBut'), {
attributes: true
});

Is it possible to listen for changes to an object's attributes in JavaScript?

Thanks for the comments guys. I've gone with the following:

var EntriesRegistry = (function(){

var instance = null;

function __constructor() {

var
self = this,
observations = {};

this.set = function(n,v)
{
self[n] = v;

if( observations[n] )
for( var i=0; i < observations[n].length; i++ )
observations[n][i].apply(null, [v, n]);

}

this.get = function(n)
{
return self[n];
}

this.observe = function(n,f)
{

if(observations[n] == undefined)
observations[n] = [];

observations[n].push(f);
}

}

return new function(){
this.getInstance = function(){
if (instance == null)
{
instance = new __constructor();
instance.constructor = null;
}
return instance;
}
}
})();

var entries = EntriesRegistry.getInstance();

var test = function(v){ alert(v); };

entries.set('bob', 'meh');

entries.get('bob');

entries.observe('seth', test);

entries.set('seth', 'dave');

Taking on-board your comments, I'll be using event delegation on the form objects to update the registry and trigger the registered observing methods.

This is working well for me so far... can you guys see any problems with this?

Detecting when data attribute changes

Well, if you can use only $.data() function, you can intercept its executions as follow:

  • Get the current jQuery's data function.
  • Execute the native jQuery's data function.
  • Get the result.
  • Execute your logic for page detection.
  • Return the result from the jQuery's data function.

var page = +$('#app').data('page');
var dataFn = $.fn.data;$.fn.data = function(value, data) { var result = dataFn.call(this, value); executePageDetection(value, data); return result;};
$('#button__page-change').on('click', function() { page = page + 1; $('#app').data('page', page);});
var executePageDetection = function() { switch (page) { case 2: console.log('page: ', page); break; case 3: console.log('page: ', page); break; default: console.log('switch statement does not appear to be working'); break; }};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="app" data-page="1"></div>
<button id='button__page-change'>Click me</button>

jQuery: Listener to input attribute change

You could use a MutationObserver:

console.log('script start');
const test = document.querySelector('#test');

new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.attributeName === 'disabled') {
console.log('Change detected');
}
}
})
.observe(test, { attributes: true });

setTimeout(() => {
test.removeAttribute('disabled');
}, 1000);
<textarea id="test" disabled>Test</textarea>

Change aria attribute value using JavaScript Observer method

So below, you have a checkbox with an event handler to toggle the aria-highlight value.

And an observer which triggers on attribute change from the div.

// Our two elements
let square = document.querySelector("#mydiv")
let chk = document.querySelector("#highlight")

// Checkbox click handler
chk.addEventListener("click", function(){
square.setAttribute("aria-highlight",this.checked)
})

// That is the function called when there is a mutation event
var callback = function(mutationsList) {
for(var mutation of mutationsList) {
if (mutation.type == 'attributes') {
console.log("The attribute '" + mutation.attributeName + "' was modified.");
}
}
};

// The mutation observer
var observer = new MutationObserver(callback);
observer.observe(square, { attributes: true });
<div id="mydiv" aria-highlight="false" style="background: red; height: 100px; width: 100px"></div>
<label for="highlight"><input type="checkbox" id="highlight">Highlight Div</label>


Related Topics



Leave a reply



Submit