Is there a way to listen for the disabled
DOM property change?
Something like this:
setTimeout(function () {
$("#myElem").prop('disabled', true);
}, 1500);
$("#myElem").on('disabled', function(e){
alert('my custom code');
});
Here's also a fiddle.
Edit: If possible, I'd like a generic solution to this. For example, in my application, I'm using an MVVM framework (Knockout), that handles internally the property change:
<button data-bind="disable: time > 3">
</button>
I'm declaring the disabling logic, but I'm not disabling it manually. What I want to do manually, is hook to that event, so I can do my custom logic.
I've seen an example here on SO:
jQuery.propHooks.disabled = {
set: function (el, value) {
if (el.disabled !== value) {
el.disabled = value;
value && $(el).trigger('disabledSet');
!value && $(el).trigger('enabledSet');
}
}
};
But this does not seem to work.
You should use Mutation Observers for this:
// Set up a new observer
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
// Check the modified attributeName is "disabled"
if(mutation.attributeName === "disabled") {
alert("disabled changed");
}
});
});
// Configure to only listen to attribute changes
var config = { attributes: true };
// Start observing myElem
observer.observe(myElem, config);
// Testing the observer gets triggered
setTimeout(function() {
myElem.disabled = true;
}, 2000);
<input id="myElem">
Though it should be noted that modern browser support is very good, IE<=10 is not supported. You might be able to get the older Mutation events to work in IE9/10, but they're not supported very well. Failing that, setInterval
can be used to "watch" the element but that should only be used as a last resort.
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