Search code examples
javascriptjquerycssparallax

How to make classic jQuery parallax more smooth


I have a classic jQuery parallax set up like this

$(window).scroll(function () {
  parallax();
});

var offset;

$(document).ready(function(){
  var p = $( ".content" );
  var offset = p.offset();
  var offset = offset.top;
});

function parallax() {
  render($(document).scrollTop());
}

function render(ev) {
  var t = ev;
  var y = Math.round(t * .25);
  $('.content').css('bottom', - y - 100 + 'px');
}

Is there a way to make it somehow more smooth?


Solution

  • You might want to try to add transition on the .content element.

    .content{
      transition: bottom 0.3s linear;
    }
    

    You will need to fire the parallax function with the same interval as you specify on the transition.

    Try something like this to fire your parallax function at the same interval:

    var interval;
    var timeout;
    
    $(window).scroll(function(event){
      //prevent from stopping the interval
      clearTimeout(timeout);
    
      //execute parallax every 300ms => same as transition
      if(!interval){
        parallax();
        interval = setInterval(function(){
          parallax();
        }, 300);
      }
    
      //stops the interval after you stopped scrolling for x amount of time
      timeout = setTimeout(function(){
        clearInterval(interval);
        interval = null;
      }, 300);
    });