Tutorial 3

Scroll to keep the fan running and the plane flying!

Airplane Airplane Airplane
Fan part 1 Fan blades Fan part 2

How it works

This tutorial will teach you how to use a scroll function to animate an object in a projectile motion.

1 >

First, store your image(s) in a div container in your HTML markup.

  

    <div class="airplane">
      
      <img src="images/airplane-01.png" class="plane-1" alt="Airplane">
      <img src="images/airplane-02.png" class="plane-2" alt="Airplane">
      <img src="images/airplane-03.png" class="plane-3" alt="Airplane">
    
    </div>

  
  
2 >

Next, style the image(s) in your CSS so they are set to "position: fixed" to make sure they stay on the screen when the user scrolls. Use top, right, bottom or left values to position your image where you would like it.

  

  .airplane {
    width: 180px;
    height: 61px;
    position: fixed;
    bottom: 300px;
    left: 100px;
    z-index: 1000;
  }

  
  
3 >

Then, add a scroll function to your window using jQuery and grab the HTML image element you are animating. Also, store the position of the image and the position of the window in variables. Use the jQuery css method to change the left, bottom, top or right value. In order to achieve a projectile/parabola movement, you have to change the position of the element on its x-axis and y-axis, so choose either top/bottom AND left/right. The math in the code below achieves a projectile movement by using cos and sin equations with the variable being the window position (pos). The if statement prevents the airplane from continuing the parabola when it's reached the "ground".

  

  $(window).scroll(function(){

    const $airplane = $('.airplane');
    const airplanePos = $airplane.offset().top;
    const pos = $(window).scrollTop();

    if(airplanePos < 2650){

    $airplane.css('left', 2*(100 + 2.5 * (pos / 7) * Math.sin(pos * 0.0009)))
                  .css('bottom', (300 + 2.5 * (pos / 7) * Math.cos(pos * 0.0009)));

    }else if(airplanePos >= 2650) {
    
    $airplane.css('left', (pos - 350));
    }

  });

  
  
BONUS >

Add this code to your scroll function in your jQuery to rotate an element just like the fan in the tutorial!

  

  $fanBlade.css({'transform': 'rotate(' + (pos) + 'deg)'});