How can I trigger an event on a nested span inside a content-editable div?

Viewed 200

I have a content-editable <div> with dynamically added <span> elements and I need to trigger a function when the user focuses on one any these span elements, either by clicking on it or using the keyboard, or if the text inside of it is changed.

I am already using a click event but I'm having trouble figuring out how to tackle the keyboard part. Any suggestions or ideas?

I've tried using 'focus' and 'change' events and they're not doing the trick. I should also mention the parent element has other event listeners attached to it so I'm not sure if that's causing issues here.

<div contenteditable="true" id="compose-box">this is some text <span class="myClass" data-index="1">special text</span>&nbsp; more text</div>
    
this.textbox = document.getElementById("compose-box");

this.textbox.addEventListener("click", (e) => {
      if (e.target && e.target.classList.contains("myClass")) {
        this.updateText(e); //Function I need to call
      }
});
1 Answers

I figured out a way to do this using the Selection object. I created a new variable to get the caret's position in the content-editable div and use it to check if the anchorNode property contained my target class.

const sel = window.getSelection();
this.textbox.addEventListener("keydown", (e) => {
      if(sel["anchorNode"] && sel["anchorNode"].parentNode.classList.contains("myClass")
      ) {
        // call method
      }
    });
Related