Search code examples
javascriptjquerycsssvgsvg-animate

Translate (gradually - with animate) an svg element after a delay using jQuery


I have this cubes which I want to translate to a different X and Y point after a delay of say 3000. I am not able to understand how to do this with the help of jQuery. Here is a JS Fiddle. Below is the code.

JS

// code for fade in one by one
console.log("game begins");
allSVGs = $("g");
fadeIn(0);
setTimeout(function () {
    $("#cubeTop").animate({
        svgTransform: "translate(0, -160)"
    });
}, 3000);

function fadeIn(svgIndex) {
    console.log(svgIndex);
    allSVGs.eq(svgIndex).css({
        "display": "block",
            "opacity": "0"
    });
    allSVGs.eq(svgIndex).animate({
        "opacity": "1"
    }, {
        complete: function () {
            svgIndex++;
            if (svgIndex < allSVGs.length) //Making sure we don't exceed the maximum available SVG elements
            fadeIn(svgIndex); //Recursively calling the next elements animation (hide) from the completed one.
        },
        duration: 400
    });
}  

Thanks in advance.

PS: Sorry for not being clear. I just made an edit to the question.


Solution

  • Well it is possible. I just made some changes to your setTimeOut. Check if this is what you want:

    setTimeout(function () {
         $("#cubeTop")
        .animate(
          {"min-height": -140},
          {duration: 1000,
           step: function( top ){
               this.setAttribute("transform", "translate(0,"+top+")");
             }
           });
    }, 3000);
    

    Here is the DEMO