Reputation: 4408
I have some elements in my HTML like a custom loading image for example that I append to the header section
<div data-role="page" id="home">
<div data-role="header" data-position="inline">
<div class='spinner'><img id="loading" src="css/images/loading.gif"/></div>
<h1>title</h1>
</div>
</div>
And To make it show I simply call the image id like $('#loading).show();
The problem is that I have this layout on other pages and when I load a new page via AJAX it appends the new DOM to the end of the document, therefore the image that is being selected is from the first page I was on NOT the second.
<div data-role="page" id="page2">
<div data-role="header" data-position="inline">
//this image will not show
<div class='spinner'><img id="loading" src="css/images/loading.gif"/></div>
<h1>title for page 2</h1>
</div>
</div>
Now I know there are work arounds for this like I can give it a class name and call it that way but this is more of a fundamental question on how jquery handles DOM injection. You would think it would be intuitive enough to find elements based off of the active page or maybe I'm missing something.
Upvotes: 2
Views: 789
Reputation: 4019
Unfortunately it isn't intuitive, there's a bit of setup to get a reliable pointer to the active page.
But yes the answer is moving towards using classes for everything and searching based on the active page, I found that using ids causes confusion because $('#id') isn't reliable anymore. I have a more complete answer here: Jquerymobile - $.mobile.changepage
If you set it up correctly it can be quite pretty:
Upvotes: 0
Reputation: 76003
The answer is also fundamental... Your IDs should be unique across the entire website when you use jQuery Mobile so you don't have the "collisions" you are getting.
You can however use the $.mobile.activePage
object to only find the element on the current page:
$.mobile.activePage.find('#loading').show();
Here is a demo: http://jsfiddle.net/QWzDB/ (notice that the alert uses text from a page that is not showing)
Upvotes: 2