I’m trying to get a function to run everytime jquery mobile loads a new page into the application, but currently, the code only gets run once on the first instance of a page loading.
HTML:
<div id="pageID" data-role="page" class="content_page">
<div data-role="header" data-id="bestHeader" data-position="fixed">
<h1>Header</h1>
</div><!-- end header -->
<section data-role="content">
<h2>Header2</h2>
<p>Content goes here</p>
</section>
<div class="bottomAd" data-role="footer" data-position="fixed">
<img src="ad2.jpg" width="100%">
</div>
<div data-role="footer" data-id="bestFooter" data-position="fixed">
<nav data-role="navbar">
<!-- navBar here -->
</nav>
</div><!-- end footer -->
</div><!-- end page -->
<div id="pageID2" data-role="page" class="content_page">
<div data-role="header" data-id="bestHeader" data-position="fixed">
<h1>Header</h1>
</div><!-- end header -->
<section data-role="content">
<h2>Header2</h2>
<p>Content goes here</p>
</section>
<div class="bottomAd" data-role="footer" data-position="fixed">
<img src="ad2.jpg" width="100%">
</div>
<div data-role="footer" data-id="bestFooter" data-position="fixed">
<nav data-role="navbar">
<!-- navBar here -->
</nav>
</div><!-- end footer -->
</div><!-- end page -->
Javascript
$(".content_page").live('pageinit', function(event) {
if ($(".bottomAd img[src*=ad]").length >= 1) {
console.log($(".bottomAd img[src*=ad]").length);
$(".bottomAd").remove();
}
No matter how many times you click back and forth between the two pages, the console.log only gets called once, and the .bottomAd class gets removed document wide on the first instance of the page getting clicked on. I’d like to have the function run everytime the page is called, so each time the “page” is checked for having an image with a src that contains “ad” in the bottomAd div on that specific page, and then removed if so.
If you want to do work on something each time a page is shown (either the first time or subsequent visits) then I suggest using
pageshow,pageinitonly fires the first time a page is shown and jQuery Mobile will keep pages in the DOM sometimes. If you want to run some code only the first time a user goes to a page then usepageinitbut bind your delegated event handler to thedocumentelement.I would also make your selector more specific (to the current page) so you don’t work on elements on pages not being viewed like so:
Your delegated event handler should bind to an element always in the DOM, for example
document:should be
Note that
.live()was depreciated in jQuery 1.7 and that.on()is the new flavor.