How to click on an element, move the mouse over other elements and then select those elements that you hovered over with JavaScript?

337 views Asked by At

I am basically trying to replicate the .selectable() method of jQuery but I need it in vanilla JavaScript. Which event listener method should I use? I've tried with mousedown, but how can I detect that another element has been visited? Here is an example on how jQuery does it: [http://jsfiddle.net/ZfevM/99/]

2

There are 2 answers

0
SirFredy On BEST ANSWER

I was able to figure it out. Had to work with mouseup and mousemove as well. Here is what I came up with and it works as expected: [https://repl.it/repls/EquatorialLumberingInfinity]

Any thoughts or alternative solutions are welcomed!

0
Dmitriy Godlevski On

You could make use of window.getSelection() and [selection].getRangeAt([index]);

document
  .getElementsByTagName('body')[0]
  .addEventListener('mouseup', 
     function(){ 
       const selection = window.getSelection(); 
       const range = selection.getRangeAt(0); 

       console.log( selection, range ) 
  })

Selection has .containsNode() function to compare against given set; Range has .startContainer and .endContainer along with .commonAncestorContainer to compare against given structure