Monday, 20 May 2013

Ensure a div is visible in mobile browser

I'm currently working on a responsive site that has a high predicted mobile user base. There are a few areas in this site where divs are revealed or hidden using jQuery slideDown(), slideUp(), hide(), show(), and sometimes modal overlays are presented to the user with a tinted blocked UI.

Sometimes on mobile devices presentation of these can be problematic - the reveal of a new div may happen fully or partially off-screen, seriously damaging the user experience. To counteract this I built a javascript function which I use after each new reveal to check if the div is viewable in the browser:

function checkIfDivIsViewable(div) {

    var $window = $(window);           
    var myTop = div.offset().top;  // top of element
    var windowTop = $window.scrollTop();           // top of window
    var windowBottom = windowTop + $window.height();  // bottom of window

    if (myTop >= windowTop && myTop <= windowBottom) {
        // div is viewable in browser, do nothing
    } else {
        // div is not viewable in browser, so scroll it
        $('html,body').animate({ scrollTop: myTop }, 300);


I tried calling this on completion of reveals, like this:
but this didn't prove too reliable. I don't know why, but it's posssibly because the div is still in motion when we're asking jQuery to assess it's position. So at the risk of appearing a bit hacky I check the display after a small delay. This seems to work fine:

//now check that the div we just revealed is visible
setTimeout(function () {
        }, 500);

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!