Search code examples
javascriptiscroll

iScroll url hash change support


This is a known issue for iScroll and it only seems to happen in iOS5 where the menu completely stops working. All my sub links in iScroll are hash anchors. Does anyone have a workaround for this?


Solution

  • The way I handled it was to hijack the anchor links themselves and replace them with scrollToElement calls instead.

    // Hijack hash anchors and scroll to them
    $('a').click ( function (e) {
        var id = $(this).attr('href');
        if (id.substr(0,1) == '#') {
            e.preventDefault();
            setTimeout( function() {
                scroller.scrollToElement ( id, 0 );
            }, 0);
            return false;
        } else {
            return true;
        }
    });
    

    This code should only hijack links that begin with #. It then handles the scrollToElement in a setTimeout which fixes some other intermittent bugs. It works well on my end as long as your anchors are properly named with id's. If you are using name attributes instead of id attributes, you'll need to rewrite these.

    This code will copy name attributes and put them in the id attribute if it is blank. You probably won't need this, though.

    $('a').each (function (i, e) {
        var n = $(e).attr('name');
        var id = $(e).attr('id');
        if ( typeof id == 'undefined' || id === null || id === '') {
            $(e).attr('id', n);
        }
    });