Reputation: 988
I'm developing an e-learning application. In one exercise, I'd like to have our students read a text, flag mistakes that I put in it and evaluate their response.
Using Rangy, I solved some problems concerning text selection (let's say there's a <p id='myText'>
containing the text to be corrected):
myText
on click. I say mark because although I do use the Selection API in the process, in the end it's about a kind of selection that's more persistent.myText.innerText
) can be marked.highlight
class.I do all of this using Vue in a few lines of codes. This function is triggered whenever I click on myText
:
highlight: function() {
// Get Selection
let selection = this.$rangy.getSelection();
// Some RegEx checking omitted
// Expand selection to word boundaries
selection.expand('word');
// Some more RegEx checking omitted
// A range represents a continuous part of selected text
let range = selection.getRangeAt(0);
// Highlight text or remove marking
let applier = this.$rangy.createClassApplier('highlight');
applier.toggleRange(range);
}
I need to compare the marked words against a list of words that actually contain mistakes, so I tried to store the indexes of each selected range. But it seems there's no function in any Browser API or in Rangy that gives me the indexes relative to the text itself, I can only get indexes relative to the HTML in myText
- which is changing with each marking or unmarking as Rangy inserts spans to highlight the words that the user selects.
Is there an elegant solution to my problem? I could store each marked word with it's left and right neighbours (text between the word and the boundaries of myText
) and compare it to a text-only version of myText
's contents, but that seems rather clumsy. Is there a better way?
Upvotes: 0
Views: 126
Reputation: 324677
There is a highlighter module in Rangy that I think sounds like what you want. Rangy also has various APIs for returning ranges and selection relative to the text within a page. Hopefully the documentation will help and I can answer questions arising.
Upvotes: 0