Skip to content

Instantly share code, notes, and snippets.

@3dd13
Created September 20, 2011 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 3dd13/1229868 to your computer and use it in GitHub Desktop.
Save 3dd13/1229868 to your computer and use it in GitHub Desktop.
Javascript to update the "top" css style after every scroll event, to solve the mobile browser position:fixed; issue. The function is called only if the client browser (by checking user-agent) is one of the mobile browsers.
var deviceIphone = "iphone";
var deviceIpod = "ipod";
var deviceIpad = "ipad";
var deviceAndroid = "android";
//Initialize our user agent string to lower case.
var uagent = navigator.userAgent.toLowerCase();
function detectUserAgent(deviceName)
{
return (uagent.search(deviceName) > -1)
}
function isMobileDevice()
{
return (detectUserAgent(deviceIphone) || detectUserAgent(deviceIpod) || detectUserAgent(deviceIpad) || detectUserAgent(deviceAndroid));
}
function updateLightboxTop() {
var win_y = $(window).height();
var scroll_y = $(window).scrollTop();
if (isMobileDevice()) {
$("#CB_Window").css({ top: (win_y * 0.5 + scroll_y) + "px" });
}
}
var showTimer = false;
function updateLightboxTopWithTimer(evt) {
if ( showTimer ) {
clearTimeout( showTimer );
}
showTimer = setTimeout( updateLightboxTop, 100 );
}
$(window).bind( "scroll", updateLightboxTopWithTimer);
@ehallgren
Copy link

Thanks for this, I developed the script a bit to prevent the timer from running unless needed and also shortened the code a bit, in this case adapted to androids but that's easily extended.

    //Initialize user agent string to lower case.
    var uagent = navigator.userAgent.toLowerCase();

    function isMobileDevice(){
        return (uagent.search('android') > -1);
    }

    function updateLightboxTop() {
        var scroll_y = $(window).scrollTop();
        console.log(scroll_y);
        $("#overlay").css({ top: scroll_y + "px" });
    }

    if(isMobileDevice()){
        $(window).bind("scroll", function(){
            var showTimer = setTimeout(updateLightboxTop, 100);
        });
    }

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