4
votes

I have an SVG object which consists of multiple paths. For each of these paths, a JavaScript function is attached to the "onmouseout" event. This is shown below:

<path id="AUK" style="fill:#00A600;" onmouseover="m_over(this.id);" onmouseout="m_out(this.id);" d="M142.3397,326l-8.66,-15l8.66,-15h17.32l8.66,15l-8.66,15H142.3397z"/>

When the user hovers their mouse over this element, the opacity is set to 0.3 (function not shown). When the user's mouse leaves this element, the opacity is reset to 1.0. The function that achieves this is shown below:

function m_out(hover_id) { 
document.getElementById(hover_id).setAttribute("fill-opacity", "1.0"); }

I want to fade (or animate ) the opacity from 0.3 to 1.0 over 1 second. Currently this transition occurs (almost) instantly.

Ideally, I would like to achieve this using code similar to whats listed above.

Where should I start...?

1

1 Answers

5
votes

You can add css transitions to your stylesheet

#AUK{
    -webkit-transition: fill-opacity 1s;
    transition: fill-opacity 1s;
}

with this you could even make this in pure css.

<style>
 circle {
    -webkit-transition: fill-opacity 1s; /* Safari */
    transition: fill-opacity 1s;
}
  circle:hover {fill-opacity:0.1}
</style>
<svg>
  <circle cx="50" cy="50" r="45" fill="blue" stroke="darkblue" stroke-width="8"/>
</svg>

If you want the transtion to work only one way (ie only on mouseout on mouseover) you can use a class selector and add or remove the class as needed.

function m_over(evt){
evt.target.setAttribute("fill-opacity","0.2")
evt.target.removeAttribute("class")
}
function m_out(evt){
evt.target.setAttribute("fill-opacity","1")
evt.target.setAttribute("class","fade")
}
<style>
 .fade {
    -webkit-transition: fill-opacity 1s; /* Safari */
    transition: fill-opacity 1s;
}

</style>
<svg>
  <circle cx="50" cy="50" r="45" fill="blue" stroke="darkblue" stroke-width="8" onmouseover="m_over(evt)" onmouseout="m_out(evt)"/>
</svg>