DominikN.
DominikN.

Reputation: 1245

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?

Upvotes: 2

Views: 185

Answers (1)

Zammy
Zammy

Reputation: 573

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);
});

Upvotes: 1

Related Questions