Codepen here.
HTML:
<input placeholder="HRM"/>
JavaScript:
let input = document.querySelector('input')
let observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === 'attributes') {
//let value = mutation.target.value
console.log(mutation)
console.log(mutation.attributeName)
}
})
}).observe(input, {
attributes: true
})
input.placeholder = 'asdfsd'
input.value = "Y U NO FIRE"
When the placeholder
attribute is changed, the Mutation Observer fires.
But when the value
attribute is changed, the Mutation Observer does not fire. Does anyone have solid understanding of why? (Hopefully backed with a link to the ECMAScript/HTML5 standards.)
Does anyone know how we can watch for when JavaScript makes changes to HTMLInputElement
's value
via input.value
?
The Mutation Observer will observe changes in the DOM but when you type text inside an input, if you inspect the DOM element, there is not change. So we need to trigger that change.
You can do that by setting the input attribute to the inserted value. See the code bellow.