John
John

Reputation: 3115

How to make a g element in an SVG clickable

I understand that it is a grouping for transformations. I have also looked through the documentation and have found nothing regarding this, but was wondering whether it is possible.

Upvotes: 1

Views: 2985

Answers (3)

Nathan
Nathan

Reputation: 437

Super old question but it helped me out so I want to expand on one of the answers with a little more of a step-by-step guide and some more details. This is the method I made when my group was several disconnected items and I wanted the whole area including the blank areas in between to be clickable.

  1. Get the x/y/width/height of the <g> element, you can do this easily in chrome dev tools by selecting the <g> element and entering $0.getBBox() in the console.
  2. Create a new element as a child of your <g> like so: <rect x="TODO" y="TODO" width="TODO" height="TODO" style="pointer-events: all" />
  3. Replace the TODO above with the info from getBBox

Upvotes: 0

GuybrushThreepwood
GuybrushThreepwood

Reputation: 153

Assign id to element, and listener. Ex.

<g id="clickg"><circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/><g>

$("#clickg").on("click",function () {
    alert("click");
});

Upvotes: 1

Robert Longson
Robert Longson

Reputation: 124059

Fill it with a <rect width="whatever the <g> width is" height="whatever the <g> height is"/> and make the <rect> clickable. The rect can be transparent check out the pointer-events property for how to configure clicability of the <rect>.

You can find the <g> height and width by calling getBBox.

Upvotes: 1

Related Questions