How do I make svg path hover area bigger

Viewed 693

What I have:

#poly-1:hover {
    stroke: green;
}
<svg width="1000" height="500" id="chart-main-canvas" style="background-color: bisque; z-index:5000;"> 
    <path id="poly-1" d="M 5,10 C 24,88 60.99999999999998,322 100,400 C 139,478 149,470 200,400 C 251,330 295,30.000000000000007 355,50 C 415,70 470.99999999999994,410 500,500" fill="none" stroke="red" style="z-index:6000;"></path>
</svg>

If I hover exactly on path, which is a tricky task, line it will change color to green.

What I want to do is to make hover area of this path bigger, so I could move my cursor somewhere +-5px near the path area and it will still change color.

The only two ways I know I could do is:

  1. Make stroke-width bigger, but I don't want its actual size with red color to increade.
  2. With my main path create invisible duplicating path that has bigger stroke-width and add condition that if I hover on it - my main path will change color.

But there is any simple way to do it?

2 Answers

This answer is practically your second option.

I'm putting the path #poly-1 in the defs and use it first with a wide stroke-width and no stroke. In order to make it sensitive to the mouse I'm using pointer-events="stroke"

<use xlink:href="#poly-1" stroke-width="10" pointer-events="stroke"/>

Next comes another use - the visible one - with a red stroke.

I'm putting both use elements in a group. The stroke of the second use element changes when I'm mousing over the group.

#group .use {
  stroke: red
}

#group:hover .use {
  stroke: green;
}
<svg width="1000" height="500" id="chart-main-canvas" style="background-color: bisque; z-index:5000;">
  <defs>
    <path id="poly-1" d="M 5,10 C 24,88 61,322 100,400 C 139,478 149,470 200,400 C 251,330 295,30 355,50 C 415,70 471,410 500,500" fill="none" >
    </path>
  </defs>
  <g id="group">
    <use xlink:href="#poly-1" stroke-width="10" pointer-events="stroke"/>
    <use class="use" xlink:href="#poly-1" />
  </g>
</svg>

I added stroke width for color change to highlight. please try this..

#poly-1:hover {
    stroke: green !important;
    stroke-width:2px;
}
<svg width="1000" height="500" id="chart-main-canvas" style="background-color: bisque; z-index:5000;"> 
    <path id="poly-1" d="M 5,10 C 24,88 60.99999999999998,322 100,400 C 139,478 149,470 200,400 C 251,330 295,30.000000000000007 355,50 C 415,70 470.99999999999994,410 500,500" fill="none" stroke="red" style="z-index:6000;"></path>
</svg>

Related