2

I'm building a text reader that renders long paragraphs of text, and will both need to register clicks on individual words and also dynamically color individual words. It does not need to be editable, however.

What is the most efficient method (suitable for modern, mobile & browser html engines) to construct this type of html? What we had previously is something where each word and space is its own span, and has listeners attached to it. This seemed rather inefficient to me.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Eric M
  • 307
  • 3
  • 9
  • That's how HTML works. Text nodes don't have any formatting properties, only elements have. – Teemu Aug 27 '15 at 16:59

1 Answers1

1

The answer at https://stackoverflow.com/a/9304990/441757 might provide some insights.

There’s a demo of it at http://jsfiddle.net/Vap7C/80/

$("body").click(function() {
    // Gets clicked on word (or selected text if text is selected)
    var t = '';
    if (window.getSelection && (sel = window.getSelection()).modify) {
        // Webkit, Gecko
        var s = window.getSelection();
        if (s.isCollapsed) {
            s.modify('move', 'forward', 'character');
            s.modify('move', 'backward', 'word');
            s.modify('extend', 'forward', 'word');
            t = s.toString();
            s.modify('move', 'forward', 'character'); //clear selection
        }
        else {
            t = s.toString();
        }
    } else if ((sel = document.selection) && sel.type != "Control") {
        // IE 4+
        var textRange = sel.createRange();
        if (!textRange.text) {
            textRange.expand("word");
        }
        // Remove trailing spaces
        while (/\s$/.test(textRange.text)) {
            textRange.moveEnd("character", -1);
        }
        t = textRange.text;
    }
    alert(t);
});
Community
  • 1
  • 1
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197