jQuery animate plane across screen - out left side - back in on right side?

Hi Eric,

I would do this:

$(function() {
  function nearClouds(){
    nearclouds.css('right', startPos);
    nearclouds.animate({right: -1268}, 60000, 'linear');
  }
  
  function farClouds(){
    farclouds.css('right', startPos);
    farclouds.animate({right: -1068}, 90000, 'linear');
  }
  
  var startPos = $(document).width();
  var nearclouds = $('#nearclouds')
  var farclouds = $('#farclouds')
  
  nearClouds();
  farClouds();
  
  setInterval(function() {nearClouds();}, 63000);
  setInterval(function() {farClouds();}, 93000);
});

I would keep the function definitions within $(document).ready() as they are only called from here (i.e. they are not needed elsewhere on the page) and in this way they don’t pollute the global namespace.

If we are just talking about these two functions then this is all I would do, as the code is still relatively readable.
If you want to animate multiple elements, I would abstract everything out into an animateMe() function.

Bit like this:

$(function() {
  
  function animateMe(el, startStyle, endStyle, duration, repeat){
    setTimeout(function(){animateMe(el, startStyle, endStyle, duration, repeat)}, repeat);
    el.css(startStyle);
    el.animate(endStyle, duration, 'linear', function(){
      el.css(startStyle);
    });
  }    
 
  w = $(document).width()
  animateMe($('#nearClouds'),{right: w}, {right: -1268}, 60000, 63000);
  animateMe($('#farClouds'),{right: w}, {right: -1068}, 90000, 93000);
});

This assumes that the elements disappear off the screen like in the last example, as the animation then starts over.
If you wanted to animate them between two points (i.e. forward and back), that would require an extra function.

Does this help at all?