How to loop in jquery once you load the page?

Asked

Viewed 233 times

0

hail personal! I have a drawing of an arrow, and I would like it to move down and up without stopping, from the moment someone loads the page.

$(document).each(function() {

  $('#seta').animate({top: "100px"}, 1000 ),
  $('#seta').animate({top : "-100px" }, 1000);

});

I did it and it seems to work, but it just goes down and up and then it stops for good. I read some jquery documentation until I arrived at this .each() but I’m having trouble understanding why it’s not working, thank you!

1 answer

1


The each() you use when you want to browse through a collection of elements with a same identifier (a class, tag, attribute, etc.). Does not apply to your case.

You can create a function that will receive a parameter (true upward, false down) to know whether the element will go up or down, and the callback animation will call the function again by alternating, creating a looping infinite:

$(document).ready(function(){
   
   (function mover(i){
      
      $('#seta').animate({top: (i ? "-" : "+")+"100px"}, 1000, function(){
         mover(!i);
      });
      
   }())
   
});
#seta{
   position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="seta">
   seta
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.