MorganFR
MorganFR

Reputation: 341

Increase clickable area of an SVG border

I have SVG shapes made from edges using stroke and no fill.

Is there a way to increase the clickable area of an SVG border?

If it were just a shape I could just add a border with stroke width to make the clickable area larger. However, I am already using the borders.

Adding a second and larger layer underneath (second "path" in the same "g" but transparent) will not work either as there is a selection mechanism in place that would break if we clicked on the second layer instead of the visible layer, as well as the fact that the elements are being redrawn (they are links between boxes in a graph and they update as I move the boxes around in real time), and the code that does that is sealed in an API. However, if the two layers could work as if there was only one in a way, that would work.

EDIT: Here's a sample of one of the shapes.

<g>
    <path class="graph_edge" d="M239.25 -185.8L290.125 
        -185.8L290.125 -281L341 -281">
    </path>
</g>

As it stands, I would rather not add an id if possible nor can i change anything about the existing path.

Upvotes: 6

Views: 3913

Answers (1)

enxaneta
enxaneta

Reputation: 33054

If you use no fill, only the stroke is clickable. You may use a transparent fill to make the shape clickable inside. However: if you want only the stroke to be clickable you can reuse your shape with <use> with a wider transparent stroke, put them both in a group and make the group clickable

#clickable:hover{cursor:pointer}
<svg width="250" height="150" viewBox="0 0 250 150">
 <defs> 
  <rect id="therect" x="20" y="20" height="80" width="100" >
  </rect>
  </defs>
  
<g  id="clickable">

<use xlink:href="#therect" stroke="#006600" stroke-width="5" fill="none" fill-opacity="0.5" />

<use xlink:href="#therect" stroke="#000" stroke-width="25" fill="none"  stroke-opacity="0" />

</g>
</svg>

UPDATE the OP comments that "each edge is made using a "path", has no id and doesn't use references." In this case:
  1. I create the array of all paths with the class .graph_edge

  2. I close the all these paths (the path the OP gave me) with javascript by adding a z to the end of the d attribute.

  3. In CSS I add a transparent border to the shape. This is increasing the clickable area of the shape but won't be visible.

PS Very strange edge shape!

let pathsArray = Array.from(
document.querySelectorAll(".graph_edge"))


pathsArray.forEach(p =>{  
  let thisD = p.getAttributeNS(null,"d");
  p.setAttributeNS(null, "d", thisD+"z")
})
svg{border:1px solid;}

.graph_edge{stroke:rgba(0,0,0,0); stroke-width:15px; cursor:pointer;}
<svg viewBox = "230 -290 120 120"><g>
    <path id="test" class="graph_edge" d="M239.25 -185.8L290.125 
        -185.8L290.125 -281L341 -281">
    </path>
</g>
</svg>

Upvotes: 3

Related Questions