hackrnaut
hackrnaut

Reputation: 583

How to target a <path> within a <svg> with Vue.js @mouseover?

Codepen with example.

I have a SVG map with various paths that hold data. What I'd like to do is pick up the state name when the path is hovered over.

I attached a event listener to the svg element and am looking for the event.target to get specific path from the event. I built the handleStateHover which logs the current event.target in the methods object:

<svg style="stroke-linejoin: round; stroke:#000; fill: none;"
     width="100%"
     height="600"
     viewBox="0 0 1000 600"
     version="1.1"
     id="svg"
     @click="handleStateClick"
     @mouseover="handleStateHover">

handleStateHover (e) {
    console.log(e.target) 
} 

The problem is, it seems like e.target logs the svg element instead of the path elements. Sometimes it does show the path element as intended but then quickly changes to the svg element again.

You can see by opening your console and looking at the JS log.

Does anyone how to get the path element on the hover event consistently? Shouldn't e.target always show the specific child element that was hovered over in the parent element? What am I doing wrong? Thanks

Upvotes: 2

Views: 3798

Answers (1)

Daniel
Daniel

Reputation: 35684

This is not exactly a vue issue, but rather just vanilla js.

Nevertheless, there are two things needed:

  1. filter to only use paths, and then get the name from the path's dataset

handleStateHover (e) { if (e.target.tagName === 'path') { console.log(e.target.dataset.name); } }

  1. add pointer-events: fill; style to svg
    By default the mouse pointer uses a box model, so your events are not going to be correctly differentiating between states

Here is a working example: https://codepen.io/anon/pen/JeGELr

Upvotes: 4

Related Questions