I’m trying to select the text and save that selection in localStorage or DB, and I could highlight the previously selected text by reading it back from the storage. But if the selected text is on multiple location in the page then all the instances get highlighted which I do not want. I can grab the left and top of the selected text but in case of font resizing, the left/top changes. I’m not sharing any code here because there is nothing to share related to this. FYI, I’m referring to iBooks app in ipad which has the same feature and I’m willing to know how does it do it properly?
Update: I tried a new approach wherein i add markers around the selected text using which I could figure out the start and end of the selected string to be highlighted later. You can see the demo here: http://jsfiddle.net/codef0rmer/jE4w5/
but in iPad rangeCount is not working, Is there any workaround for iPad?
You can get information about the current selection using
window.getSelection()– at least in modern browsers. It will return a Selection object, you could start with playing with the properties supplied by that object:anchorNode
Returns the node in which the selection begins.
anchorOffset
Returns the number of characters that the selection’s anchor is offset within the anchorNode.
focusNode
Returns the node in which the selection ends.
focusOffset
Returns the number of characters that the selection’s focus is offset within the focusNode.
isCollapsed
Returns a Boolean indicating whether the selection’s start and end points are at the same position.
rangeCount
Returns the number of ranges in the selection.
Also, using the
getRangeAt()method, you could get the Range objects from the Selection, which supply more useful methods and properties.I don’t know how far you want to go with this solution, and your question is quite general, so this is more like a direction you could go rather than a ready-to-use solution.