Home > Software engineering >  Bring front of the selected SVG path
Bring front of the selected SVG path

Time:09-03

I want to bring front of the selected SVG path. I used Z-index and position relative property. Could not find out the solution.

Three pink shapes on top of each other on a graph paper background. The bottom-most has a dashed selection outline rectangle.

CodePudding user response:

Move given node (shape or group) in the source structure after those you want to "cover".

CodePudding user response:

A Native JavaScript Web Component <svg-hover> gives you the flexibility to easily re-use code on multiple SVGs, without having to worry about JavaScript load order as Web Components will 'upgrade' undefined DOM elements automatically.

A [hover] attribute makes it easier to target the SVG elements within a more complex SVG

If you don't need multiple listeners on one SVG element, you might as well use the inline Eventhandler.

<svg-hover>
  <svg viewBox="0 0 600 180">
    <rect   hover  x="0" y="0" width="150" height="150" fill="red" stroke="black"></rect>
    <rect   hover  x="125" y="50" width="150" height="150" fill="yellow" stroke="black"></rect>
    <circle hover  cx="175" cy="100" r="100" fill="blue" stroke="black"></rect>
  </svg>
</svg-hover>

<script>
customElements.define("svg-hover", class extends HTMLElement{
  connectedCallback(){
    setTimeout(()=>{ // make sure <svg> was parsed, thus available in the DOM
      let svg = this.querySelector("svg");
      this.querySelectorAll("[hover]")
          .forEach(el => el.onmouseenter = (evt) => svg.append(el))
    });
  }
});
</script>

  • Related