0

I have a button on click of which a fish appears and it should randomly over a container at random places. but in my code its just animating only once and not repeating overand overagain. I want my function to be generic so that it can be run over and over of many fishes and be efficient code.

The HTML:

  <input type="button" value="Post" class="post-button" />

The jQuery:

var idgenerated=0;
$('.post-button').on('click',function(e){
    //$('#container img:last-child').append('<div class="small-fish"> </div>');
    $('#rightarrow').after('<div class="fishhatch" id="'+idgenerated+'"></div>');
    $('.pop-up-selectCategory').hide(); 
    $('.oyster').removeClass('oyster-click');
    animatenewfish(idgenerated);
    idgenerated++;  
}); 

function animatenewfish(idgenerated) {
    console.log("hi");
    var Fishv1 = $("#"+idgenerated),
    theContainer = $("#container"),
    maxLeft = theContainer.width() - Fishv1.width()-100,
    maxTop = theContainer.height() - Fishv1.height()-100,
    leftPos = Math.floor(Math.random() * maxLeft),
    topPos = Math.floor(Math.random() * maxTop),
    imgRight = "Assets/R1gif.gif",
    imgLeft = "Assets/FIsh1.gif";
    console.log(maxLeft+"max");
    console.log(leftPos+"travel");
    if (Fishv1.position().left < leftPos) {
        Fishv1.css("background-image",'url("' + imgRight + '")');
    } else {
        Fishv1.css("background-image",'url("' + imgLeft + '")');    
    }

    Fishv1.animate({
        "left": leftPos,
        "top": topPos
    }, 18000, animatenewfish);
}
vzwick
  • 11,008
  • 5
  • 43
  • 63
user3218194
  • 448
  • 4
  • 15

3 Answers3

0

put your animation in

setInterval(function(){
    Fishv1.animate({
        "left": leftPos,
        "top": topPos
    }, 18000, animatenewfish(idgenerated));
},18000);

so it will be called after each 18000 milliseconds.

Swanand
  • 1,138
  • 8
  • 21
0

change code Where you are calling your function This code will call function every 500 ms.

  /*Jquery Code*/
  var idgenerated=0;
  $('.post-button').on('click',function(e){

    //$('#container img:last-child').append('<div class="small-fish"> </div>');
    $('#rightarrow').after('<div class="fishhatch" id="'+idgenerated+'"></div>');
    $('.pop-up-selectCategory').hide(); 
    $('.oyster').removeClass('oyster-click');
    setInterval(function() { animatenewfish(idgenerated); }, 500);        
    idgenerated++;

}); 
shyammakwana.me
  • 5,562
  • 2
  • 29
  • 50
0

The animate takes an optional callback

Fishv1.animate({
    "left": leftPos,
    "top": topPos
}, 18000, animatenewfish(idgenerated));

How can I loop an animation continuously in jQuery?

Community
  • 1
  • 1
Kivylius
  • 6,357
  • 11
  • 44
  • 71