Skip to content

Instantly share code, notes, and snippets.

@filmaj
Created September 10, 2010 22:36
Show Gist options
  • Save filmaj/574501 to your computer and use it in GitHub Desktop.
Save filmaj/574501 to your computer and use it in GitHub Desktop.
Poor man's JavaScript scrolling helper for mobile devices
function PoorMansGloveBox(element) {
this.element = element;
this.parentHeight = this.element.parentNode.clientHeight;
this.element.style.position = 'relative';
this.element.style.top = '0px';
this.lastPos = 0;
this.currentPos = 0;
var self = this;
this.element.addEventListener('touchstart', function(e){
self.lastPos = e.touches[0].pageY;
}, false);
this.element.addEventListener('touchmove', function(e){
self.currentPos = e.touches[0].pageY;
var deltaY = self.currentPos - self.lastPos;
var newPos = (parseInt(self.element.style.top.substr(0,self.element.style.top.length-2)) + deltaY);
if (newPos > 0) newPos = 0;
var viewportDelta = (self.element.clientHeight - self.parentHeight)*1.2;
var maxScrollBottom = viewportDelta<=0?viewportDelta:viewportDelta*-1;
if (newPos < maxScrollBottom) newPos = maxScrollBottom;
self.element.style.top = newPos + 'px';
self.lastPos += deltaY;
}, false);
}
@purplecabbage
Copy link

function PoorerMansGloveBox(element) {
var parentHeight = element.parentNode.clientHeight;
element.style.position = 'relative';
element.style.top = '0px';
var lastPos = 0;
var currentPos = 0;

element.addEventListener('touchstart', function(e){
      lastPos = e.touches[0].pageY;
}, false);
element.addEventListener('touchmove', function(e){
    currentPos = e.touches[0].pageY;
    var deltaY = currentPos - lastPos;
    var newPos = (parseInt(element.style.top.substr(0,element.style.top.length-2)) + deltaY);
    if (newPos > 0) newPos = 0;
    var viewportDelta = (element.clientHeight - parentHeight)*1.2;
    var maxScrollBottom = viewportDelta<=0?viewportDelta:viewportDelta*-1;
    if (newPos < maxScrollBottom) newPos = maxScrollBottom;
    element.style.top = newPos + 'px';
    lastPos += deltaY;
}, false);

}

@filmaj
Copy link
Author

filmaj commented Sep 10, 2010

Always gotta one up me eh!

Cheers mang, doubling up on variables in a closure = stupid.

@purplecabbage
Copy link

Just playin, no up'g
Could probably tweak/squeeze a little more, but it's cool!

@purplecabbage
Copy link

waiting to see the Poorest!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment