Trigger SVG stroke-dashoffset animation with a click event once more

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>

Answer №1

To kickstart the animation, I rely solely on JQuery while the rest is handled by CSS. I've included a checkbox in your HTML that governs the animation. Although the checkbox is visible, you have the option to hide it using CSS (visibility:hidden or display:none). I trust this aligns with your desired outcome.

$(label).click(function(){
    $(this).addClass("test");
});
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;
  left: 0;
  top: 0;
}

#umriss {
  stroke-dasharray: 2333.43;
  stroke-dashoffset: 2333.43;
} 
.test #umriss {  
  animation: ani1 4s linear forwards;}


[type="checkbox"] {
  position: absolute;
  top: 0;
  left: 0;
}

[type="checkbox"]:checked + label #umriss {
  animation: ani2 4s linear forwards;
}


@keyframes ani1 {
  from {
    stroke-dashoffset: 2333.43;
  }
  to {
    stroke-dashoffset: 0;
  }
}

@keyframes ani2 {
  from {
    stroke-dashoffset: 0;
  }
  to {
    stroke-dashoffset: 2333.43;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <div class="wrapper">
        <div class="bild">
        <input type="checkbox" id="anim"/>
        <label for="anim" id="label">
            <svg id="form" x="0px" y="0px" width="200" viewBox="0 0 812.959 581.971">
                <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>
          </label>
        </div>
</div>

UPDATE

Within the CSS script, I've utilized the :checked selector to initiate different animations.

Animation without checkbox usage:

In this scenario, I'm employing the click event to append the .test class to bild. Additionally, I make use of the animationend event to remove the .test class. I hope this explanation clarifies the process for you.

bild.addEventListener("click",()=>{
  bild.classList.add("test")
})


//umriss.addEventListener("webkitAnimationEnd",..... );
umriss.addEventListener("animationend",()=>{
  console.log("end")
  bild.classList.remove("test");
} );
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;
  left: 0;
  top: 0;
}

#umriss {
  stroke-dasharray: 2333.43;
  stroke-dashoffset: 0;
} 
.test #umriss {  
  animation: ani1 4s linear forwards;
}

@keyframes ani1 {
  from {
    stroke-dashoffset: 2333.43;
  }
  to {
    stroke-dashoffset: 0;
  }
}
 <div class="wrapper">
        <div id="bild">
            <svg id="form" x="0px" y="0px" width="200" viewBox="0 0 812.959 581.971">
                <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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlimited Possibilities in Designing Shared React Components

Seeking the most effective strategies for empowering developers to customize elements within my React shared component. For example, I have a dropdown and want developers to choose from predefined themes that allow them to define highlight color, font siz ...

TinyMCE's Textarea is blank and not displaying any content

I can't seem to figure out where I went wrong with using TinyMCE. I downloaded it from and chose version 4.0.3. After downloading, I ended up with a folder called tinymce_4.0.3 which contained subfolders like tinymce_4.0.3\tinymce\js\t ...

How can a borderless text field be created using Material UI?

Today, I delved into using Material UI for my React project. My goal is to create a registration form similar to this one. Essentially, I want 5 input text fields without any borders and with a simple background color effect when active. However, I'm ...

The functionality of the Bootstrap 4 Carousel featuring multiple items is experiencing malfunctions

I'm encountering an issue with my Bootstrap 4 card carousel. When the next or prev buttons are clicked, there is a strange transition effect. Additionally, in the mobile version, the buttons do not work properly. It seems that when the card slides to ...

Duplicating an array retrieved through a jQuery ajax request

Currently, I am encountering an issue while attempting to duplicate a JSON array within this specific JavaScript function: var test = new array(); function showUser(user, pass, remember) { $.getJSON("login.php", { username : user, password : pass, che ...

Placing an image within a table row that spans multiple rows to maintain center alignment in relation to other rows that are not span

Having trouble with centering the image in an email signature when viewed in GMail. The layout works fine in JSBin but appears uneven in GMail. Any suggestions on how to make sure it stays centered? Check out the code here https://i.sstatic.net/F2LXV.png ...

Updating the DOM after making changes with Maquette involves calling the `renderMaquette

In a previous discussion, I expressed my desire to utilize Maquette as a foundational hyperscript language. Consequently, avoiding the use of maquette.projector is essential for me. However, despite successfully appending SVG objects created with Maquette ...

Transmitting a Page (View) to an Ajax Function in CodeIgniter

Currently, I am using Codeigniter alongside the Zurb Foundation framework. My objective is to load data into a reveal box (a fancy popup) using AJAX. The challenge here is that I do not want to just load the inner HTML content, but rather the entire HTML i ...

Creating HTML elements using JavaScript's Document Object Model

I am trying to create an img tag dynamically using JavaScript with the following code: <img id="drag0" src="http://localhost:34737/Images/MainSlider/A(1).jpg" class="col-4" draggable="true" ondragstart="drag(event)"> and I have a drag method setup ...

Guide on incorporating interactive visuals or features within a panoramic image viewer through the use of THree.js and webGL

Seeking advice on how to incorporate more images and hyperlinks within a panoramic viewer, similar to the examples below: This particular link Panorado js viewer. I have noticed that these viewers feature embedded hyperlinks and overlays, I have attempt ...

tips for recognizing the selected element

seeking assistance in resolving the issue with the script. once the user selects an item .menu_button, a function called initForm() is invoked. This function is expected to output only console.log(N) but instead, it outputs 3: console.log(1) console.l ...

What steps can I take to enhance the responsiveness and overall performance of this code using bootstrap?

Struggling with making your website responsive? No worries, we've all been there. Whether you're a pro at coding in react.js and vue.js or a complete beginner, we all need to start somewhere. Any suggestions or tips on how to improve responsivene ...

Struggling to execute a custom SQL update method in .NET through jQuery, encountering various errors like 404 and 500

I am attempting to invoke a .NET method from a JavaScript file within a Web Form project. I am uncertain if my approach is correct and I am encountering difficulties in debugging the process. .NET method: [System.Web.Services.WebMethod] public st ...

Is there a way to create a universal script that works for all modal windows?

I have a dozen images on the page, each opening a modal when clicked. Currently, I've created a separate script for each modal. How can I consolidate these scripts into one for all modals? <!-- 1 Modal--> <div class="gallery_product col-lg-3 ...

Try utilizing MutationObserver to monitor changes in various nodes

I am faced with a situation where I have elements in my HTML that are dynamically populated with text from an API. My goal is to check if all these elements have a value and then trigger a function accordingly. The current code I have only allows me to obs ...

jQuery if statements not correctly functioning when using multiple conditions

Previously, this code was functioning correctly: if (item.isPrivateToSubOrg == false){ However, after adding this line of code, it stopped working: if (item.isPrivateToSubOrg == false && item.eventStatus == 'Published'){ I'm retr ...

Prevent clicks from triggering on dynamically loaded ajax content within a DIV

I am seeking help on how to prevent click events from being triggered on dynamically loaded content within a specific DIV element. <div id="left_column"> <div class="menu">------</div> <div class="menu">------</div> ...

Tips for adjusting column width with flexbox intersections

I am currently working on a React web application that has minimal styling. I have divided the content into 3 columns, with the leftWrap being col-3, rightWrap being col-4, and the remaining width is for centerWrap. I want to apply flex ...

Exploring MongoDB through User Interface Requests

As part of a project to develop a minimalist browser-based GUI for MongoDB, an interesting question has arisen. How can we accurately display the current state of the database and ensure it is continuously updated? Specifically, what methods can be utiliz ...

Enhance your HTML rendering with Vue.js directives

Check out this cool code example I created. It's a simple tabs system built using Vue.js. Every tab pulls its content from an array like this: var tabs = [ { title: "Pictures", content: "Pictures content" }, { title: "Music", c ...