Jason Taylor
Jason Taylor

Reputation: 3

Parallax choppy

I have a basic parallax effect on my website. However, it is quite choppy and I am unsure why. My code is below.

function parallax(){
  var $parallax = $('.parallax');
  var $scrollPos = window.scrollY;

  $parallax.css('transform', 'translateY(' + -($scrollPos * 0.3) + 'px)');
}

$window.scroll(function(){
  //Check for mobile
  if(!/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ) {
    // You are in mobile browser
    requestAnimationFrame(parallax);
  }
}

Upvotes: 0

Views: 307

Answers (1)

Soviut
Soviut

Reputation: 91595

You should move your user agent check outside the scroll event. Right now you're performing an uncompiled regular expression hundreds of times whenever a user scrolls their browser.

// cache the result of the user agent test
var isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent);

$window.scroll(function(){
  if (!isMobile) {
    requestAnimationFrame(parallax);
  }
}

Additionally, it's generally recommended that you DO NOT do user agent checks since they're very fragile; User agent strings can be spoofed, new browsers are released, etc. Instead you should use feature detection or simply do what CSS designers do with media queries and check the width of the screen. If the screen is too narrow, assume you're on a small screen that shouldn't do parallaxing.

var parallaxEnabled = false;

// only update the variable if the browser resizes (fires when device changes orientations too)
$window.resize(function() {
    // enable parallax if greater than 720 pixels (ipad portrait)
    parallaxEnabled = document.width > 720;
});

$window.scroll(function() {
  if (parallaxEnabled) {
    requestAnimationFrame(parallax);
  }
});

Upvotes: 3

Related Questions