Home > Back-end >  Detect click inside an svg javascript
Detect click inside an svg javascript

Time:02-03

<div id="anim">
    <svg>
        <defs><clipPath id="__lottie_element_2"></defs>
        <g>
            <g ></g>
            <g id="bbbbb"></g>
            <g id="ccccc"></g>
        </g>
    </svg>
</div>

Detect when I click on inside id="anim" and throw an alert. alert("you have pressed class" aaaa) Detect when I click on id="bbbbb" inside id="anim" and throw an alert. alert("you have pressed id" bbbbb)

thank you

    window.addEventListener("load", function () {
    
    
    let element = document.querySelector("div.anim > svg > g > g").getAttribute("id");

    element.addEventListener("click", function() {
    alert("You clicked");
    

      });
      

CodePudding user response:

You can use the closest() function to find the parent <g> that was clicked. The <g> does not itself take any click events, so you rely on the content of the <g>.

And you just need one event listener for the entire thing. e.target is the element that was clicked (depending on how you use pointer-events if that is something you can use in your case).

window.addEventListener("load", function() {
  let element = document.querySelector("div#anim");

  element.addEventListener("click", e => {
    let gclicked = e.target.closest('g');
    alert(`You have pressed class ${gclicked.getAttribute('class')}`);
  });
})
<div id="anim">
  <svg viewBox="0 0 30 10" width="300">
    <g >
      <circle r="5" cx="5" cy="5" fill="red"/>
    </g>
    <g >
      <circle r="5" cx="15" cy="5" fill="blue"/>
    </g>
    <g >
      <circle r="5" cx="25" cy="5" fill="orange"/>
    </g>
  </svg>
</div>

CodePudding user response:

window.addEventListener("load", function() {
  // `div.anim` means div with class anim
  // why would you use `getAttribute` here?
  let element = document.querySelector("div#anim > svg > g > g");

  element.addEventListener("click", function() {
    alert("You clicked");
  });
})
<div id="anim">
  <svg>
        <!-- you forgot to close `<clipPath>` -->
        <defs><clipPath id="__lottie_element_2"></clipPath></defs>
        <g>
            <g ></g>
            <g id="bbbbb"></g>
            <g id="ccccc"></g>
        </g>
    </svg>
</div>

  • Related