Recently, I created a simple SVG stroke animation using CSS and jQuery. The animation triggers on a click event, but I'm struggling to figure out how to restart it on a second click, or subsequent clicks. I've tried various methods like using .addClass, but nothing seems to work. Here's how I envision it working:
1. The stroke is visible
2. User clicks on the image
3. Stroke animation begins
4. Once the animation is complete, the stroke remains visible
5. User clicks again
6. Stroke animation restarts ...
Here's the current code snippet I have:
jQuery(document).ready(function () {
$("#form").click(function () {
var path1 = document.querySelector('#umriss');
var length = path1.getTotalLength();
$(path1).css("stroke-dasharray", length);
});
});
body {
width: 100%;
font-size: 20px;
background-color: #eee;
}
.wrapper {
margin: 0 auto;
text-align: center;
max-width: 700px;
}
.bild{
width: 100%;
height: 0;
padding-top: 100%;
position: relative;
}
svg{
position: absolute;
height: 100%;
width: 100%;
left:0;
top:0;
}
#umriss {
stroke-dashoffset: 2600;
animation: ani1 4s linear forwards;
}
@keyframes ani1 {
to {
stroke-dashoffset: 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Stroke</title>
</head>
<body>
<div class="wrapper">
<div class="bild">
<svg id="form" x="0px" y="0px" width="812.959px" height="581.971px" viewBox="0 0 812.959 581.971" enable-background="new 0 0 812.959 581.971" xml:space="preserve">
<path id="umriss" fill="#3CC243" stroke="#141412" stroke-width="10" stroke-miterlimit="10" d="M137.521,128.454 C139.812,9.278,220.056,16.972,313.194,20.365c136.466,4.97,179.837,72.616,205.304,200.859
c21.428,107.905,195.473,45.773,260.65,56.229c39.317,6.308-28.293,212.529-53.685,245.178
c-61.222,78.716-262.76,32.434-351.007,35.777c-102.917,3.899-125.172-88.539-81.979-175.921
c71.457-144.56-162.979-48.431-225.951-44.29C-22.9,344.077,25.05,112.387,137.521,128.454z"/>
</svg>
</div>
</div>
</body>
</html>