Search code examples
htmld3.jssvghovermousehover

Hover event on lineargradient colors in svg


I have an SVG rectangle filled with a lineargradient that has various <stop offset = ..> to make it filled with different colours. I'm trying to make a different text appear (one text per colour) every time i hover with the mouse on that specific color. To make it clear:

When i hover over the orange in the rect i want "Orange" to appear. When i hover over the red in the rect i want "Red" to appear.

But i cannot figure out how to approach this. Is there any way?

Here is my code:

<svg>
<g class="nodes">
<rect id="13" class="startNode" x="0" y="0" width="100" height="540" freq="1" ref="13"
    style="fill: url("#fill-13"); cursor: pointer; opacity: 1; visibility: visible;">
</rect>
<linearGradient id="fill-13" gradientTransform="rotate(90)">
    <stop offset="0%" style="stop-color:#ffe154; stop-opacity: 1.0"></stop>
    <stop offset="37%" style="stop-color:#ffe154; stop-opacity: 1.0"></stop>
    <stop offset="37%" style="stop-color:#009600; stop-opacity: 1.0"></stop>
    <stop offset="48%" style="stop-color:#009600; stop-opacity: 1.0"></stop>
    <stop offset="48%" style="stop-color:#ff54ff; stop-opacity: 1.0"></stop>
    <stop offset="49%" style="stop-color:#ff54ff; stop-opacity: 1.0"></stop>
    <stop offset="49%" style="stop-color:#5151ff; stop-opacity: 1.0"></stop>
    <stop offset="55%" style="stop-color:#5151ff; stop-opacity: 1.0"></stop>
    <stop offset="55%" style="stop-color:#ff0000; stop-opacity: 1.0"></stop>
    <stop offset="67%" style="stop-color:#ff0000; stop-opacity: 1.0"></stop>
    <stop offset="67%" style="stop-color:#59bdff; stop-opacity: 1.0"></stop>
    <stop offset="100%" style="stop-color:#59bdff; stop-opacity: 1.0"></stop>
</linearGradient>

Solution

  • As I've commented: It would be easier to use several rects each with a different fill color instead of using one rect with a linear gradient.

    let svg = document.querySelector("svg")
    svg.addEventListener("mouseover",(e)=>{
      output.innerHTML = e.target.getAttribute("class")
    })
    svg{border:solid}
    <p id="output">color</p>
    <svg viewBox="0 0 100 540" width="50">
      <g class="nodes">
        <rect width="100"  height="37%"
    fill="#ffe154" class="yellow"/>
        <rect width="100" y="37%"  height="11%"
    fill="#009600" class="green"/>
        <rect width="100" y="48%"  height="1%"
    fill="#ff54ff" class="purple"/>
        <rect width="100" y="49%"  height="6%"
    fill="#5151ff" class="blue"/>
        <rect width="100" y="55%"  height="12%"
    fill="#ff0000" class="red"/>
        <rect width="100" y="67%"  height="33%"
    fill="#59bdff" class="skyblue"/>
      </g>
    </svg>