jQuery Mobile: In-Page Hash Links

A client of mine had an existing HTML document with a bunch of anchor tags linking to hashes within the page.  Since jQuery mobile uses the hash for it’s ajax loading the #top, #whatWeCollect and so on links would of course trigger a new (non-existent) page to load.

To get around this limitation in jQuery Mobile I wrote a little script.  It will essentially look for a class on the anchor tag and then do a little JavaScript magic to link to the in-document hash location.  Essentially recreating normal browser activity.


		var $target = $(this).parents('.ui-page').find($(this).attr('href')).eq(0);
		if($target.length == 1)

Essentially, what is going on here is that when a “page” is loaded by jQuery Mobile, I am looking for a wrapper element with the class “retroHashes”. Inside this element is the old [ugly] code I got from my client.

Then I look for all the anchor tags where the href begins with the hash.  If it does I unbind anything that might have been attached to click by other methods.  Not very nice and you might not want to do that step but in my case I was fragging all other behaviors on these links.

I bind new functionality to the click.  stopPropagation() prevents jQuery Mobile from doing it’s ajax load.

The rest is finding the target.  In my case the client was setting the the id of the target element and not the name, so I can actually just use the href attribute of the link as the selector.

I check to make sure that I found a target, and scroll to the offset within the document.

There you have it.  A quick hash link hack for jQuery Mobile.  If people like it I may expand this example to more use cases.

Leave a Reply

Your email address will not be published. Required fields are marked *