1

I have a <span> element which holds some content in it. The content changes when you type something. How can I listen to those events?

For Example :

<span> Start content </span>

After some content change

<span> Changed content </span>

Is there any way I can listen to the key events (like keyup, blur)?

Chris
  • 57,622
  • 19
  • 111
  • 137
Mari Selvan
  • 3,598
  • 3
  • 21
  • 36
  • 3
    How does the content change _"when you type something"?_ This isn't natural behavior - do you have something like `contenteditable` on the span or an input with an attached event? – Lewis Jul 16 '19 at 09:55
  • 2
    `` is a static element. You're not supposed to be able to type anything in it, it's not an ``. How do you achieve this? – Jeremy Thille Jul 16 '19 at 09:55

3 Answers3

6

You can listen out for the DOMSubtreeModified event.

However, this doesn't sound like a good idea. You said:

Is there any way I can listen to the key events (like keyup, blur)?

You should use a call this code next to the code where you change the content of the span. Otherwise, you should be using an input element to listen out to the events you listed.

Here is an example using the DOMSubtreeModified event:

const content = document.getElementById('content')
const append = () => content.innerText += ' change'

content.addEventListener('DOMSubtreeModified', () => console.log('change'))
<span id="content">Content</span>
<br>
<button onclick="append()">Change content</button>

Here are examples using change (which acts similarly to blur, but only triggers if there's a change) and keypress events:

const content = document.getElementById('content')

content.addEventListener('change', () => console.log('change'))
content.addEventListener('keypress', () => console.log('keyPress'))
<input type="text" id="content" value="Content">
Kobe
  • 6,226
  • 1
  • 14
  • 35
  • DOMSubtreeModified support is deprecated in major browser (see https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent). MutationObserver should be used instead. – Francois Connetable Jul 18 '23 at 08:13
1

you can use DOMSubtreeModified to track changes on your span element. Refer the below question for further assistance,

Trigger for span text/html on changed

Kural
  • 202
  • 1
  • 9
0

To do this you should use a Mutation observer (see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver). You would do something along those lines:

let observer = new MutationObserver((list, obs) => {
    console.log('Something has changed!')
})
let targetSpanElement = document.querySelector('span'); // use what selector works for you!
observer.observe(targetSpanElement, {
  characterData: true,
  childList: true,
  subtree: true
})