Question

I want to ask question is it something possible with text range or other approach. I have a text. For example like this:

<div id="test">abcdefghij</div>

I use text range to highlight fragment of text with yellow color. (I use example posted into SO). It is possible to add event listener for mouser over on highlighted text? I want to do something when user mouseover on 'cdefg'. Here is working jsfiddle.

http://jsfiddle.net/8mdX4/673/

I would appreciate any ideas and recommendations.

Best regards.

Edit:

I want to share the approach that I have usied after the topic. I'm using focusNode property of selection because commonAncestorContainer get container of all nodes - not that node currently selected. Here is demo: http://jsfiddle.net/zono/Q3ptC/2/ Mouseover on yellow text displaing tooltip (content of title property).

Was it helpful?

Solution

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:

http://jsfiddle.net/8mdX4/680/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top