Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listening for an element disable event

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.

like image 888
Zubzob Avatar asked Jun 24 '15 13:06

Zubzob


1 Answers

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.

like image 198
CodingIntrigue Avatar answered Oct 02 '22 04:10

CodingIntrigue