Mahdi Bashirpour
Mahdi Bashirpour

Reputation: 18803

jQuery: Listener to input attribute change

<textarea id="test" disabled>Test</textarea>

Is there a way to listen to the changes in the attributes? such as disabled attribute.

I need an event to add or remove "disabled" attr. Something like this:

$("#test").on("change attribute",function(){
    alert("Textarea enabled");
})

Upvotes: 1

Views: 73

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370699

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>

No external libraries like jQuery needed; this is supported in essentially all browsers nowadays.

Upvotes: 2

Related Questions