jQuery mobile finds elements from first page when on second page - jquery-mobile

I've got a two page jQuery mobile app, and within the init function, the following code..
Call to the init function
$(document).on('pageinit', function(){
MyPages.init();
});
init: function() {
$('td[id$="drops"]').each(function() {
console.log("Element: " + $(this).attr('id'));
}),
};
I have elements in page one that match the above, such as '#early_drops', '#late_drops', etc. These elements do not exist on page 2, but when page 2 loads, the elements are displayed in the console just like when page 1 is loaded. What am I missing here?
Thanks very much,
-Adam vonNieda

By default jQuery loads pages using AJAX into the existing page in order to allow the animated transitions. If you don't want this you just need to 'turn off' the AJAX loading.
See description here: http://view.jquerymobile.com/1.3.2/dist/demos/widgets/links/
Links that point to other domains or that have rel="external", data-ajax="false" or target attributes will not be loaded with AJAX. Instead, these links will cause a full page refresh with no animated transition. Both attributes (rel="external" and data-ajax="false") have the same effect, but a different semantic meaning: rel="external" should be used when linking to another site or domain, while data-ajax="false" is useful for simply opting a page within your domain from being loaded via AJAX.
You can also disable AJAX across the entire app by default using global configuration: http://api.jquerymobile.com/global-config/

Related

jQuery mobile force full reload when link clicked

I have a "normal" link in my jqm page like this:
<a href="http://www.mysite.com/mobile/page.php?attribute=value">
And if I click it it won't properly refresh taking into account the attribute value and loading everything that's needed for it dynamically based on the attribute value. I understand that this is due to the fact that jqm tries to do an ajax call like mentioned here:
When you use pageChange an Ajax request will be made to that url and it will be
loaded only the content inside the div with data-role="page". So everything you
have out of this element will be ignored (JS and CSS).
So, I found out in the docs that I should use $.mobile.ajaxEnabled=false; or rel=external on links or target=_blank on the link.
Strange thing though for me is that only when I set the target=_blank property to my links will this truly happen. So, am wondering if someone had this kind of a problem and how did you solve it? The thing is, I would like to refrain myself form using target=_blank as it opens a new tab in my browser (as expected, but this is not nice from users' POV).
jqm version I use is 1.2
This question now at the top of google search results, so figured I'd answer:
Use the data-ajax attribute and set it to false to force reload upon clicking a link:
data-ajax="false"
use it like:
<a href="/" data-ajax="false">
<img id="mainLogo" src="logo.svg" width="215" />
</a>
And then your link will force reload the page!
Linking without Ajax
Links that point to other domains or that have rel="external",
data-ajax="false" or target attributes will not be loaded with Ajax.
Instead, these links will cause a full page refresh with no animated
transition. Both attributes (rel="external" and data-ajax="false")
have the same effect, but a different semantic meaning: rel="external"
should be used when linking to another site or domain, while
data-ajax="false" is useful for simply opting a page within your
domain from being loaded via Ajax. Because of security restrictions,
the framework always opts links to external domains out of the Ajax
behavior.
Parts taken from https://stackoverflow.com/a/22951472
Make function for the onclick event of the link.See the below code example.Hope this helps!
<script type="text/javascript">
function loadPage(url){
document.location.href = url;
}
<script/>
<a href="#" onClick="loadPage('http://www.mysite.com/mobile/page.php?attribute=value');">

AngularJS + Twitter Bootstrap: Changes remain on partial after change (jQuery Mobile)

I am trying to build a single page application that has three views using angular and bootstrap. I am new to angular and I want to implement the following:
In jQuery Mbile it is possible to have three different chats on three different pages..if I am currently on Page A, the chats in Pages B and C are still ongoing. Hence, navigating through pages does not stop processes on the other ones.
Please correct me if I'm wrong. I want to know how I can switch between multiple views/templates on the same partial/page in angular the way i can navigate between divs with data-role="page" in jQuery Mobile? Is it a good idea to combine jQuery Mobile with angular and bootstrap? (I really don't think it is)
First, whenever a route changes, angular refreshes the view. The only way to prevent this is to set the "reloadOnSearch" parameter in the route to false. Once you've done this, you can pass querystring parameters to the view without reloading the view. There is an added caveat in that you have to explicitly listen for "$routeUpdate". Following is the angular code, below that is a fiddle that accomplishes your goal of switching between multiple chats without refreshing the view. I use ng-show to show the appropriate chat based on the passed querystring parameter.
angular.module('app',[]).config(function($routeProvider){
$routeProvider.when('/', {templateUrl: 'view.html', reloadOnSearch:false});
}).controller('controller', function($scope, $routeParams){
$scope.$on('$routeUpdate', function(value) {
$scope.id = $routeParams.id;
});
}).directive('chat', function(){
return{
restrict:'E',
replace:true,
scope:{},
controller: function($scope){
$scope.items = [];
$scope.submit = function(text){
$scope.items.push(text);
};
},
templateUrl:'chat.html'
}
});
http://jsfiddle.net/jwanga/u2RrU/

Custom changePage on jquery mobile causes c.data("page") is undefined on second call

I'm trying to build some custom navigation in a dynamic application, all screens are obtained from the server and thus I registered the pagebeforechange event and execute my own function.
Everything works as I expected except when I refresh the data I destroy the dynamic pages and try to call the page I was in again using the page Id, but this second time, although my code creates the HTML for the page, jQuery Mobile throws an "c.data("page") is undefined" error.
I bind the pagebeforechange event:
$(document).bind('pagebeforechange', function(e, data) {
if(typeof data.toPage === 'string') {
appobj.dynamicPage(data.toPage, data.options);
}
});
Then in the dynamicPage method I create the HTML for my page based on Underscore.js templates and let jQuery continue changing the page:
$.get('templates/page.tpl.html', function (data) {
html = _.template(data, { /* several template parameters */});
});
page = $(html);
page.appendTo('body').page();
The idea was to use as much of jQM as possible since I'm creating the destination page and injecting it into the DOM.
When I need to update the supporting data, that I store in localStorage, I just find all dynamic pages and destroy them:
var current = $.mobile.activePage.attr('id');
$('.dynamicpage').remove();
$.mobile.changePage('#' + current
When running the application I can easily navigate between various screens/pages, even for pages that don't exist when the application starts but if the data needs to be updated (because the user added elements in the application of data in the database changed) then the removal code is executed but the old page is not regenerated ending in a white page with all the DOM contents hidden, but the page I wanted to navigate too seems to be in the DOM (at least firebug tells me so).
If I were to restart development I would probably use Backbone.js to handle my model updates and view changes but for now I'll have to use only jQM. Any suggestions? I understand that jQM is not finding my page but I don't see why since my event should be called and the page regenerated, even with the allowSamePageTransition flag set.
Regards,
Sérgio Lopes

jQuery Mobile breaks my site

I load jQuery Mobile on my site when I am only on a mobile touchscreen device. When I do though. It messes up everything. For example, select menus don't work quite right, as well, the words "loading, loading, undefined" appear at the bottom of the page. I know I am missing something but do not know what.
Any ideas on what I could be missing?
Thanks
EDIT: Okay, So I took out all scripts that I am running except for jQuery and jQuery Mobile. I call jQuery first, then jQuery Mobile. It still breaks aspects of the site.
What it breaks:
- I cannot navigate to any other page via the navbar, if I click on a nav item, and look in the url, the correct url appears (with a # in it) like: /#/about-us/ Then, it just redirects to the home page and the page goes white
Select menus have weird results. It prints out whatever is in the select right beside it. And if you in landscape mode on the ipad and you click on the select, it sends you to the bottom of the page (weird).
it prints out 'loading' twice and 'undefined' once at the bottom of the page
All I have for scripts are jQuery and jQuery Mobile. I should also mention that I am using wordpress so it might have enqueued some other scripts (I have deregistered Wordpress' version of jquery and enqueued my own)
Anyone else experiencing these problems?
jQueryMobile replace your normal links with Ajax one, so every page can be loaded by the ajax, text on docs page:
(..) Ajax is used to load the contents of each page into the DOM as you navigate, and the DOM ready handler only executes for the first page. To execute code whenever a new page is loaded and created, you can bind to the pageinit event. This event is explained in detail at the bottom of this page.
If you want to disable single link to be loaded by the ajax you should write something like this:
<a href="/some_page" data-ajax="false" >link</a>
or do it globally:
$(document).bind("mobileinit", function() {
$.mobile.ajaxEnabled = false;
});
jm also does replacement on other elements so you should try using data-role attribute, for example:
<select id="test" data-role="none">
to disable replacing this element.
For those like me where
$.mobile.ajaxEnabled = false;
did not work and the whole page layout seems still broken:
For me this one works (- set it inline before loading the jquery mobile file):
<script>
// Preload configuration
$( document ).on( "mobileinit", function() {
$.mobile.autoInitializePage = false; // This one does the job
});
</script>
Furthermore if you want to disable jQuery mobile automatic link and form handling via ajax, set (as dvk3 said) ajaxEnabled to false and pushStateEnabled to false as recommended:
$.mobile.ajaxEnabled = false;
$.mobile.pushStateEnabled = false; // Recommended is false, when ajax is disabled
For further information see: http://api.jquerymobile.com/global-config/
I'm using v1.4.5
Same happened to me by mixing mobile with other frameworks. Fixed issue but getting custom build of jQuery.mobile. My case was that I needed swipe for touch devices only so used custom min file and nothing was broken after that.
It really depends if you need jQuery.mobile or you need just a certain functionality, Widgets, events? Use custom version that you can build yourself.
You can make and download yours here : http://jquerymobile.com/download-builder/
I hope it worked for you too guys!

jQuery Mobile Page refresh mechanism

I'm having a lot of pain understanding how jQuery Mobile handles pages refresh after an ajax update.
I'm having a two pages - unique file site: a search engine.
First page is a search field. Submit triggers a JSON call and parser which updates the second page: results.
for now i'm using: $.mobile.changePage( $('#result') ); which does the job great from search field to result page.
However:
If I reuse it from result page for next/prev pages ( new json call, new parse, new added nodes in the DOM );
Jquery Mobile just don't "paint" the newly added nodes.
can anyone explain, please the use and distinction of
1- $.mobile.page()
2- $.mobile.changePage()
3- $.mobile.refresh()
or give me a hint on how I should handle page changes.
thanks!
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0
Please take a good look here: http://jquerymobile.com/test/docs/api/methods.html
$.mobile.changePage() is to change from one page to another, and the parameter can be a url or a page object. ( only #result will also work )
$.mobile.page() isn't recommended anymore, please use .trigger( "create"), see also: JQuery Mobile .page() function causes infinite loop?
Important:
Create vs. refresh: An important distinction
Note that there is an important difference between the create event and refresh method that some widgets have. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method that some widgets have should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.
For example, if you had a page where you dynamically appended a new unordered list with data-role=listview attribute after page creation, triggering create on a parent element of that list would transform it into a listview styled widget. If more list items were then programmatically added, calling the listview’s refresh method would update just those new list items to the enhanced state and leave the existing list items untouched.
$.mobile.refresh() doesn't exist i guess
So what are you using for your results? A listview? Then you can update it by doing:
$('ul').listview('refresh');
Example:
http://operationmobile.com/dont-forget-to-call-refresh-when-adding-items-to-your-jquery-mobile-list/
Otherwise you can do:
$('#result').live("pageinit", function(){ // or pageshow
// your dom manipulations here
});
I posted that in jQuery forums (I hope it can help):
Diving into the jQM code i've found this solution. I hope it can help other people:
To refresh a dynamically modified page:
function refreshPage(page){
// Page refresh
page.trigger('pagecreate');
page.listview('refresh');
}
It works even if you create new headers, navbars or footers. I've tested it with jQM 1.0.1.
I found this thread looking to create an ajax page refresh button with jQuery Mobile.
#sgissinger had the closest answer to what I was looking for, but it was outdated.
I updated for jQuery Mobile 1.4
function refreshPage() {
jQuery.mobile.pageContainer.pagecontainer('change', window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
// 'reload' parameter not working yet: //github.com/jquery/jquery-mobile/issues/7406
});
}
// Run it with .on
$(document).on( "click", '#refresh', function() {
refreshPage();
});
I solved this problem by using the the data-cache="false" attribute in the page div on the pages I wanted refreshed.
<div data-role="page" data-cache="false">
/*content goes here*/
</div>
In my case it was my shopping cart. If a customer added an item to their cart and then continued shopping and then added another item to their cart the cart page would not show the new item. Unless they refreshed the page. Setting data-cache to false instructs JQM not to cache that page as far as I understand.
Hope this helps others in the future.
This answer did the trick for me http://view.jquerymobile.com/master/demos/faq/injected-content-is-not-enhanced.php.
In the context of a multi-pages template, I modify the content of a <div id="foo">...</div> in a Javascript 'pagebeforeshow' handler and trigger a refresh at the end of the script:
$(document).bind("pagebeforeshow", function(event,pdata) {
var parsedUrl = $.mobile.path.parseUrl( location.href );
switch ( parsedUrl.hash ) {
case "#p_02":
... some modifications of the content of the <div> here ...
$("#foo").trigger("create");
break;
}
});

Resources