You are using document.execCommand
a lot in your code to style elements, this will most likely create a <span>
but that's up to the browser. When doing so, each browser will create elements in your target text as it sees fit. To my knowledge, there is no event management command available when using execCommand, so using this technique will make specific event assignments difficult to these elements.
If I were to write your code from scratch, I would use an approach with window.getSelection
and create the elements myself, so that I could add the events as I see fit.
Another alternative is just to add window.getSelection() once you know that execCommand
has created an element, find the selection's parent, and add the event to the parent node. Like this:
/*At a point where I know a selection is made*/
var sel = window.getSelection();
if (sel.rangeCount) {
parent = sel.getRangeAt(0).commonAncestorContainer
if (parent.nodeType != 1) {
parent = parent.parentNode
}
parent.onclick = function() {
alert("lookie lookie");
}
}
Your code updated with my example: