BeetleJuice
BeetleJuice

Reputation: 40896

HTML Textarea: how to be notified when value changes (input event not triggered)

My front end application needs to auto-adjust a textarea height when its contents change. I can partially get this to work by reacting to the input event, like so:

textarea.addEventListener('input', adjustSize);

The problem is that this is not triggered when the value is set in code:

textarea.value = 'some new value';

Is there an elegant way to capture these changes as well? One option I have seen mentioned is to manually trigger the event, but that won't work for me because the context where I need to react to the change and do the resize obviously doesn't know when the change has occured, and the context where I make the change doesn't know that some other piece of code needs to know when value changes.

var textarea = document.getElementById('myInput');

textarea.addEventListener('input', adjustSize);

// this does not trigger the event handler
setTimeout(write, 1000);

function adjustSize() {
  console.log('adjustSize');
}

function write() {
  textarea.value = 'new textarea value';
}
.myInput {

}
<textarea id="myInput" class="myInput">
  I am textarea
</textarea>

Upvotes: 0

Views: 3562

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65806

Because you are making the changes via code, you'll need to use a DOM Mutation Observer that can monitor the element for changes. But, don't set the value of the textarea, instead the value of a textarea is its content, so set the textContent.

var textarea = document.getElementById('myInput');

textarea.addEventListener('input', adjustSize);

setTimeout(write, 1000);

function adjustSize() {
  console.log('adjustSize');
}

function write() {
  // Don't set the value, change the content
  textarea.textContent = 'new textarea value';
}


// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Create an observer instance linked to the callback function
const observer = new MutationObserver(adjustSize);

// Start observing the target node for configured mutations
observer.observe(textarea, config);

// Later, you can stop observing
//observer.disconnect();
.myInput {

}
<textarea id="myInput" class="myInput">
  I am textarea
</textarea>

Upvotes: 2

Related Questions