Jeremy P. Beasley
Jeremy P. Beasley

Reputation: 709

JS/CSS Solution for on scroll events, compatible with mobile Safari

Within many web apps, I often have the need for a JS and/or CSS solution that allows me to change CSS values on objects (incrementally) as the user scrolls down/up on the page.

http://codepen.io/bsley/pen/gGyhm

function EasyPeasyParallax() {
  var scrollPos = $(document).scrollTop();
    $('.header').css({ 'opacity': 1-(Math.min(scrollPos/70,1)) });
};

$(document).ready(function() {
    $('body').bind('mousewheel', EasyPeasyParallax);
});

The issue with the above code is two-fold.

  1. It only allows me to control the math based on a PX variable and not any percentage relative to the height or width of the screen. This is important with varying screen sizes.

  2. It's not compatible with Mobile Safari at all.

Any help on how I could accomplish the same with but meet the two points above?

Upvotes: 2

Views: 319

Answers (3)

jilykate
jilykate

Reputation: 6008

Just for the second point (I believe you already know how to solve the first one)...

Mobile browsers (especially Safari) do not support real 'scroll' events. They just fire the scroll event once after the target stops scrolling. The view stops rendering while scrolling, so you can not change 'opactiy' dynamically according scrollTop. What you need is a lib like 'iscroll' to handle the scroll event

Upvotes: 0

Joe
Joe

Reputation: 2596

To fix your mobile safari issue, bind to the scroll event instead of mousewheel.

$(document).ready(function() {
  $('window').bind('scroll', EasyPeasyParallax);
});

As far as percentages go, you'll have to calculate them yourself using some other values.

function EasyPeasyParallax() {
  var scrollPos = $(document).scrollTop(),
      bodyHeight = $('body').height(),
      viewportHeight = $('window').height(),
      scrollPercentage = (scrollPos / bodyHeight) * 100;
  $('.header').css({ 'opacity': 1-(Math.min(scrollPos/70,1)) });
};

Upvotes: 2

ckersch
ckersch

Reputation: 7687

You can apply .css styles inline with pure javascript. Just use:

var nodes = document.getElementsByClass('header');

var i = 0;

for(var i = 0; i < nodes.length; i++){
   nodes[i].style.opacity = .5;
   nodes[i].style.left = someLeftVal + '%';
}

You can compute any percentages you need.

Upvotes: 0

Related Questions