0

When I move my finger, I want it to automatically highlighted the words that I go through. I saw some solutions that require long pressing then selecting the words, I want to bypass this. This features usually present in most IOS PDF viewers like PDF expert, it is also available on Apple book. I like apple book implementation, I want to copy it to any HTML.

Is this possible to do?

My current code works with clicking a word then highlight, I tried touchmove but it doesn't work


document.addEventListener('click', function(e) {


  var selectedVocabPhrase = null
  var matchedVocabPhrase = null
  var selection = window.getSelection()

  if (selection.anchorNode.parentNode.nodeName === 'STRONG') {
    selectedVocabPhrase = selection.anchorNode.parentNode.innerText
  }
  if (!selection || selection.rangeCount < 1) return true;
  var range = selection.getRangeAt(0);
  if (range.startOffset !== range.endOffset) {
    // User selected at least one character themselves; don't change anything
    return;
  }
  var node = selection.anchorNode;

  var word_regexp = /^(?:|\S*(?![.,])\S)$/;

  // Extend the range backward until it matches word beginning
  while ((range.startOffset > 0) && range.toString().match(word_regexp)) {
    range.setStart(node, (range.startOffset - 1));
  }
  // Restore the valid word match after overshooting
  if (!range.toString().match(word_regexp)) {
    range.setStart(node, range.startOffset + 1);
  }

  // Extend the range forward until it matches word ending
  while ((range.endOffset < node.length) && range.toString().match(word_regexp)) {
    range.setEnd(node, range.endOffset + 1);
  }
  // Restore the valid word match after overshooting
  if (!range.toString().match(word_regexp)) {
    range.setEnd(node, range.endOffset - 1);
  }

 var sel = window.getSelection();
       sel.removeAllRanges();
          sel.addRange(range);
                                         document.designMode = "on";
          document.execCommand("hiliteColor", false, "yellow");
          sel.removeAllRanges();
                                document.designMode = "off";

document.activeElement.blur(); 
        
})

I tried How to Select text on mobile web browser by moving touch on screen using javascript?. It is messy and require two touches.

0 Answers0