Parallax Effect

J-Query can make your page magical !!

21st October, 2017

When developing webpage j-query can be of great help in enhancing the look and feel of your webpage.
Like, if you see above the background scrolls at a different speed than the other text. This is Parallax Effect.
Now, to achieve this you need a few lines of J-Query code.

  • Suppose we have a small piece of HTML with a small div element.

    HTML

    <div class="jumbotron">

       <h3> Some heading </h3>

    </div>

  • Lets add some CSS styling.

    CSS

    .jumbotron {

       height: 600px;

       background: url('jumboImage.jpg') center center no-repeat;

       text-align: center;

    }

  • Time for some JS magic - What we need to do is basically everytime user scrolls the page, we need to call a helper funciton to animate the background. We can do this by binding the helper funciton to the scroll event on window.
    $(window).bind('scroll', animateJumbotron);

    After this, we need to change the background position depending on the amount of page scrolled by the user. We keep track of this by using
    var pos = $(window).scrollTop();

    Then we just need to get a new position of background depending on the amount of page scroll done by user and change the CSS property for the element with the new value.

    To make things more clear, the code would look something like this -

    JS

    $(document).ready(function () {

       $(window).bind('scroll', animateMenu);

       function animateMenu() {

         var pos = $(window).scrollTop();

         var velocity = 0.05;

         $('.jumbotron').each(function () {

           var backHeight = 50 + pos * velocity;

           $(this).css('backgroundPosition', '50% ' + backHeight + '%');

         });

       }

    });

    Tip: The variable 'velocity' is used to set the speed with which the background image scrolls. Increase the velocity's value for a greater speed.

Great job. You just added a great J-Query animation to your web page.

Hope you liked it and found it useful.
Follow to get more blogs like this.
Would love to hear from you people be it for suggestions , corrections or just chat.
Mayank Jain