console.clear();
document.addEventListener('mouseup', e => console.log("Stop"))
// Keyboard keys
document.addEventListener('mousedown', e => console.log("Hold ") )
Please Click on This Blank Space to simulate the mouseup and mousedown event.
Have a great day !!
let paths = document.querySelectorAll('path');
// paths is an html collection of all paths;
// attach event listeners to each path;
for (let i=0; i<paths.length; i++) {
paths[i].addEventListener('click', event => console.log(event.target.dataset.key));
}
<div>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="800pt" height="600pt" viewBox="0 0 800 600 " id="svg1">
<g enable-background="new">
<path data-key="Line_1" transform="matrix(1,0,0,-1,0,600)" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none" stroke="#000000" d="M 224.34 585.57 L 244.34 586.6 "/>
<path data-key="Line_2" transform="matrix(1,0,0,-1,0,600)" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none" stroke="#000000" d="M 124.34 545.57 L 144.34 546.6 "/>
<path data-key="Line_3" transform="matrix(1,0,0,-1,0,600)" stroke-width="6" stroke-linecap="round" stroke-linejoin="round" fill="none" stroke="#000000" d="M 174.34 545.57 L 204.34 546.6 "/>
</g>
</svg>
</div>
Above code when the 3 lines are clicked, it will output which lines are clicked with its id. In order to increase user-friendliness, I have this idea of implementing a feature, when the mouse is pressed and hold, it will keep on clicking on the cursor with of course, some time interval to prevent lagginess, which means if the cursor is hovered over those 3 lines, it will actually clicked on them without user having to click each of the lines multiple times, and when the mouse is released, it will stop the clicking on the cursor which means it will not be clicking on the lines anymore. And then, I can find the unique of the Lines array generated from the clicking to see which Lines are selected using the mouse press and hold functionality which is pretty cool :). May I know how to achieve this? I will appreciate any help I can get 🙂
2
Answers
I think you are trying to click(from code) when hovering an element continuously by just
hover
the mouse pointer on it. I believe my piece of code will help.We have a hover method which contains two call back methods.
For click and hold, try using below method as you written in your codepen demo.
I have used element
path
for adding listeners instead of document(moved those set of code inside for loop)You can use the function Document.elementFromPoint() to get an element at some position. The position comes from an object that is updated each time the mouse is moving. The setInterval() function will call the function elementFromMousePosition() will console.log the key if the element has one.
The interval is stopped either if the mouse is up or leaves the SVG.