01101011 01101111 01100100 01101001 01101110 01100111

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.

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.

Update:

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