Sunday, July 22, 2012

Anchor links and JQuery Mobile

So you need to link to an anchor inside a JQuery Mobile page, and things aren't working? Look no more, here is the answer!!!

Anchor links look like this:

<a href="#my-anchor">Link</a> 

The problem with JQuery Mobile (JQM) is that it uses the "#" sign to name pages. So instead of interpreting the above link as "open page.html and scroll to anchor #my-anchor" it will understand it as "open page #my-anchor" and obviously it won't work.

Instead, just use the following code in your page:

The link target

<div id="my-anchor">Your content</div>

The link origin

<a href="#my-anchor" class="anchor-link">My link</a>

Javascript code

$(document).ready(function() {

    $('a.anchor-link').click(function(e) {
        // Extract the hash in the target. 
        // No hash means that the target is not an <a> tag but one of its children (i.e. an <h3>)
        hash =  $(e.target).get(0).hash;
        if (!hash) {
            hash = $(e.target).parents('a').get(0).hash;
        }
        // Find the page it is contained into (or it is itself)
        page = $(hash).closest('div[data-role="page"]').get(0);
        
        // Look if we are already in that page
        if ($(page).get(0) != $.mobile.activePage.get(0)) {
            // Change to it and scroll to the anchor
            $.mobile.changePage($(page));
            $(page).on('pageshow', function(){
                $.mobile.silentScroll($(hash).offset().top);
            });
        } else {
            // Just scroll to the anchor
            $.mobile.silentScroll($(hash).offset().top);
        } 
    });
});

1 comment:

  1. Harrah's Hotel & Casino Perryville, MS - JM Hub
    Harrah's offers a 구미 출장마사지 full range of gaming and live entertainment for your favorite games. 광주 출장마사지 From slots 강원도 출장안마 to 경상북도 출장안마 table games and 화성 출장안마 keno, there's something for everyone.

    ReplyDelete