Element ID’s must be unique across all webpages in jquerymobile/ajax navigation

I’m still trying to wrap my head around jQueryMobile and its subtle nuances and differences from regular web programming. I learned the following lesson the hard way.

We know that you shouldn’t have more than one element on a webpage with the same ID. But did you know you should be careful of having the same ID even across pages? I sure didn’t.

jQueryMobile relies on ajax and does something funky with page transitions. When you click on a anchor tag to another page, you’d expect it to discard the old page and load the new one new. But that’s not exactly how it works.

The content of the new page is loaded within the first page. This has some consequences.

First, the DOM of the first page is still lingering around. So if you go to another page with an element of the same ID, guess what happens? Your guess is as good as mine. If you try to reference an element like $(‘#uniqueID’), you’ll be in for a sore surprise. It will arbitrary pick one, or probably the one on the initial page.

So what can you do about this. One solution is to make sure your IDs are unique across all pages. But what if you reference elements by class and that’s shared across pages? Beats me.

I’m still in search of a good solution. Another one proposed is to get the active page and passed that into jquery for reference.

$(document).on("pagecontainershow", function () {
   var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
   if (activePage.attr("data-url") == "page2.html") {
      // target content within active page
      // Or activePage.find("#content").css...
      $("#content", activePage).css({ color : "green" });

Solution originally provided here.


So that was easy, eh? …wait, don’t forget what happens to any variables you set in the first page (and other pages) as you navigate around.



Here’s another way to refresh the state of everything. You can add data-ajax=”false” to the anchor tag to make it load the new page as if you typed it into the address bar. This will bypass the ajax navigation. Solution suggested by @Omar

Tagged , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: