Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
javascript: restart SVG animation

according to MDN SVG Animation, I am trying to restart all animation of a svg tag by clicking on window.

function restartAnimation(el){
    [
        'animate',
        'animateColor', 
        'animateMotion',
        'animateTransform',
        'set', 
    ].forEach(tag=>{
        el.querySelectorAll(tag).forEach(ele => {
            console.log(ele.getStartTime());
            ele.beginElementAt(ele.getStartTime());
        });
    });
}

window.addEventListener('click', ()=>{
    restartAnimation(document.querySelector('svg'));
});
<svg id="svg1" viewBox="0 0 200 200" style="width: 50%; height: 50%;">
  <path d="M69 0L97 53L0 125" stroke="black" fill="none" stroke-width="5" stroke-linecap="round" id="svgPath1" style="animation: svgPath1Anim 1000ms ease-in-out 1000ms 1;">
    <animate id="animStroke1" xlink:href="#svgPath1" attributeType="XML" begin="1s" dur="2s" repeatCount="1" additive="sum" attributeName="stroke" values="silver;wheat;lightgreen"></animate>
  </path>
</svg>

I used to use ele.beginElement(), but it ignores the starting time begin="1s", which the animation starts immediately without delay.

However, after change to ele.beginElementAt(ele.getStartTime()), it does not work properly. when I click on window, I am expecting 1 to always be logged, but it gives me accumulated non-sense which

1
4.7121100425720215
11.299739837646484

I wonder why this happen. I will be so glad if you can fix the function for me.


I am currently using this

function whatTime(str){
    if(str.includes('ms')){
        return parseFloat(str.slice(0, -2)) / 1000; 
    }
    return parseFloat(str.slice(0, -1)); 
}

function restartAnimation(el){
    [
        'animate',
        'animateColor', 
        'animateMotion',
        'animateTransform',
        'set', 
    ].forEach(tag=>{
        el.querySelectorAll(tag).forEach(ele => {
                    setTimeout(()=>{
                        ele.beginElement();
                    }, whatTime(ele.getAttribute('begin')) * 1000);
        });
    });
}

window.addEventListener('click', ()=>{
    restartAnimation(document.querySelector('svg'));
});

it works, but I wonder why the previous one perform oddly.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!