JQuery Mobile - Run load () html and navigate () immediately afterwards. - javascript

JQuery Mobile - Run load () html and navigate () immediately afterwards.
I'm implementing a small application using jQuery Mobile where I have a login screen that gives access to a home with menus that lead to a few pages. My question is how can I dynamically load the pages only when I click on the menu.
I tried to do something like
$('#home').load('home.html');
$.mobile.navigate("#home");
but despite the effect of the load carrying navigate does not work, or does not redirect to the page.
Can anyone give me a hint how to do this?

You just need to use a callback. Because load is asynchronous, you actually end up calling $.mobile.navigate before load has finished. By sending the next step as a callback, you ensure it happens after you have completed the first step.
From jQuery Documentation:
If a "complete" callback is provided, it is executed after
post-processing and HTML insertion has been performed. The callback is
fired once for each element in the jQuery collection, and this is set
to each DOM element in turn.
So your code would look like:
$( "#home" ).load( "home.html", function() {
$.mobile.navigate("#home");
});

Related

jQuery function and Page Reload issue (maybe)

I have this code (accepted solution).
This code snipped loads from a js file. When I put a breakpoint at this function, I see that this function getting called when the page (that includes it) is loaded.
After the initial page load, when I choose an option in this page, that anchor element is reloaded (Ajax) exactly same (js file does not reload) as part of the piece of data. However, now when I click on anchor link, it does not fire / open the outlook window.
Is it something about jQuery functionality that I am mis reading/using?
How do I resolve this?
If the element is reloaded you'll need to rebind the click event to it.
Alternatively to the way you are doing it you could bind to the window/body and just specify the id as the selector like this:
$('body').on('click', '#emailLink', function (event) {
// your code here...
});

Get the loaded page in jQuery Mobile 1.4.2

I'm used to the older jQuery Mobile interface where I could write:
$("#page").on("pageLoad", function(){
//Do something
});
With the newer pageContainer widget and it's events, I do not know to do detect what page was loaded.
For example, I need to know how to detect that the #settings page was just loaded. So far I can figure out
$("body").on( "pagecontainerload", function( event, ui ){});
but I have no way of knowing what page was loaded. I've tried using the returned event and ui values but without success.
It seems part of my problem is coming from improper use of
$("body").pagecontainer("load", "welcome.html");
I use that in the beginning of my js file to load them all into the DOM. However, when I navigate to that page, then away from it again it is removed from the DOM. For example, I load welcome.html, settings.html, and devices.html with the above code. Then, I have links like
Settings
And when I use that link to go to the settings page, then another of the same kind of link to go to the devices page, the settings link no longer works. Upon inspecting the DOM, #settings has been removed. Infact, so has #welcome. As soon as I navigate away from that page it is removed from the DOM. So either I have done something wrong, or my understanding of the pagecontainer widget is flawed.
Update
Based on your updated OP, external pages are removed once you navigate away from them, this is the default behavior of jQM. If you want to keep those pages, you need to add data-dom-cache="true" to page div of each external page.
You can retrieve page loaded from ui object emitted on pagecontainerload.
$(document).on("pagecontainerload", function (e, ui) {
var loadedPage = $(ui.page),
pageID = loadedPage[0].id;
if (pageID == "settings") {
/* code */
}
});
Note that pagecontainerbeforeload, pagecontainerload and pagecontainerfail, are only emitted on pages loaded externaly. Moreover, they will fire everytime an external page is loaded, unless DOM cache is enabled. Read more about those events here.
Demo

How can I delay page transition in jQuery Mobile until page data is ready?

I have a mobile single-page web application that is built using jquery-mobile (jqm) and knockout. The application itself has multiple pages but they are all contained within a single HTML document.
Problem: after changing my "create view model for page" from sync to async behavior, I have the problem that jquery-mobile fires its events before the data is ready.
Background: up until recently I had been working with sample data, basically a huge JSON blob, and everything worked smoothly. With the new async composition of view models from various sources, data is not ready immediately and my "buildViewModel" method takes a continuation callback instead of just synchronously returning data.
I'm subscribing to the pagebeforecreate and pagebeforechange events, and fire off the code to populate the viewmodel here. The problem is that after returning from the event handler, jqm triggers the remaining chain of events before the data is available. This causes a page transition to an unprepared page, which is undesirable.
I have tried to call event.preventDefault in all of the before-events and manually calling $.mobile.changePage once the page is ready to be a) enhanced and b) the page transition to occur, but without any luck.
I've scanned the jquery-mobile source, but couldn't spot anything that looked like it would allow me to delay the pagebeforeshow event, which is essentially what I need in order to be able to render the page properly.
How can I ensure that 1) data is available and 2) knockout has been applied to perform initial DOM manipulations, before jquery-mobile attempts to enhance the page and before it executes the in-transition to the page?
I also considered using synchronous ajax to fetch resources, but this will (I think) not work for resources loaded from the device (using PhoneGap/Cordova), and has other negative consequences that I'd like to avoid.
FWIW, I'd like to avoid having to manually handle all navigation events by wiring up click-handlers everywhere, but I'm open to all solutions if need be.
Apologies if this is a duplicate; I've searched and read a ton of questions, but not found an answer or question that was quite the same. It just sounds incredible that I would be the first to hit this problem, as I imagine it is a common scenario..
Update: clarified problem scenario description.
I had this exact same problem.
The only solution I've been able to come up with is to write a custom transition handler that defers starting the transition until the Ajax request completes.
Here's a fiddle showing the technique. The fiddle doesn't use Knockout, but does show how to defer the transition.
Basically, since $.ajax() returns a promise, I can pipe that into the promise returned by the default transition handler and return it from my new handler.
In my pagebeforeshow handler, I attach the Ajax promise to the page so that the transition handler has access to it. Not sure if this is the best way, but I liked it better than using a global variable.
The only thing I didn't like about this is that it delays the start of the transition until the Ajax response arrives so it could feel like the page has "hung" to the user making them click again. Manually showing the loading message makes it feel a bit more responsive.
Hope this helps and please let me know if you find a better solution!
Delaying the transition to a new page until its content is ready is a very common issue when facing dynamic content in jQuery Mobile. The most convenient ways to address this are:
Instead of classic href type navigation, base the links on "click" actions that will first retrieve the content, build a new page in the DOM, and then initiate a transition to this new page through $.mobile.changePage. The advantage of this approach is that it is easy to put in place, the disadvantage is that you do not navigate with classic href links
Bind the pagebeforechange event at the document level to detect if upon navigation the target page is one of your page that should contain dynamic content. In such a case, you can prevent default navigation from happening, take your time to generate the page, and transition upon success. This is described in the JQM docs on dynamically injected content. The advantage is that you can still rely on standard href links navigation, but it requires a bit more code and design upstream to properly detect and act upon navigation to the pages.
$(document).on( "pagebeforechange", function( e, data ) {
if ( typeof data.toPage === "string" ) {
if ( data.toPage === "myDynamicPageName" ) {
e.preventDefault(); //used to stop transition to the page (for now)
/*
Here you can make your ajax call
In you callback, once you have generated the page you can call
$.mobile.changePage
(you can pass the Div of the new page instead of its name as
the changepage parameter to avoid interrupting again the page change)
*/
}
}
});
Set your link to call a "load" function instead of doing a page transition. In your load function, display the "loading message" and make the JSON call. Finally, in the JSON callback function, change page to page2
The load function:
function loadPage2() {
/* show wait page */
$.mobile.loading( 'show', {
text: 'Loading massively huge dataset',
textVisible: true
});
/* perform JSON call then call callback */
}
Callback function
function callback() {
$.mobile.changePage("#page2");
}
Here is a working JSFiddle: http://jsfiddle.net/8w7PM/
Note that if you don't want users to be able to update input fields in Page 1 while waiting, introduce a "wait page" between page 1 and page 2, with the init of "wait page" doing the same as "loadPage2".
I think you have to fire again for all widget which you want to bind the data from response to
For example, you will have to invoke trigger with create or refrestevent for the element
$("#element").trigger('create');
JQuery Mobile will bind all default events to the element as it is
--- EDIT ---
I just created a sample code, I think it's same your issue, please try the link http://jsfiddle.net/ndkhoiits/BneqW/embedded/result/
Before rending the data, we have to invoke to service to get them for displaying, that why all events binded by jqm will be removed then.
I have a workaround for this, don't make jqm fire anything on the element, we'll trigger it after all data is binded by knockoutjs
Let try the fixed version
http://jsfiddle.net/ndkhoiits/c5a2b/embedded/result/
This is the code http://jsfiddle.net/ndkhoiits/c5a2b/
I have a small jQuery Mobile / KnockoutJS application and have struggled with the very same issue. My app contains about 5 pages. All are contained in a single physical HTML document with the standard <div data-role="page"> markup separating individual pages.
I finally went with click based navigation and fire $.mobile.changePage() as the result of $.ajax success.
One of the downsides to this technique is that you will lose your button highlighting when relying on onclick vs href attributes. See my related post: href vs scripted page transitions and button highlighting
I later chose to supply both and rely on the href to perform the navigation while using onclick to invoke my JavaScript logic to load ViewModels etc. The only place that I have found this to be an issue is when there is possible validation required on the source page. If it fails, the transition has already started and the UI then flashes back to the source page. Ugly but this only happens in limited instance within my app.
I don't think any of this is specific to Knockout. My exact solution may present issues for you in that your navigation is likely to complete before your model is fully loaded but if you rely on $.mobile.changePage(), it should all work and hide your page until after it is loaded. The transitions should work fine.
<a href="#MyNewPage" data-bind="click:LoadNewPage" data-role="button">
Load Page
</a>
$.ajax({
url: url,
cache: false,
dataType: "json",
data: requestData,
type: "POST",
async: true,
timeout: 10000,
success: function (data, textStatus, jqXHR) {
// use either href or changePage but not both
$.mobile.changePage("#NewPage");
},
error: function (jqXHR, textStatus, errorThrown) {
alert("AJAX Error. Status: " + textStatus);
// jqXHR.status
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
}
});
You should place the code for the page transition in a success function on the AJAX call.
$.ajax({
url:"request-url",
data: data,
type: "POST",
success: function(response){
// Add Transition Code Here
}
});

Load 3rd Party JavaScript when user clicks an element

I know I can inject the script when the user clicks an element by creating a script element and injecting it on the page via document.appendChild. However, the script is listening for onload and onDOMContentReady (or their own home grown domReady event, not sure).
If I inject the script only when the user clicks an element, the callbacks for onload/onDOMContentReady will never fire because those events have already passed.
Any ideas? This 3rd party script pulls in all these other requests and it's not optimal for page loading.
EDIT: I read the question again...and if you are using something like jQuery, it will fire your handler function in any other document ready calls even if document ready has already been fired. It will just execute the function right away. If you are looking for a pure javascript way to do it, you need to take extra consideration to check to see if dom ready has already been fired, and fire your function yourself, otherwise attach it to the dom ready callback.
I don't see a problem with just doing something like this (with jquery for brevity):
// on document ready
$( function() {
// attach the click handler
$('#loadScript').click( function( e ) {
// on click, get the script
$.getScript('path/to/your/script.js', function() {
// your script is loaded, so what you need from here
// to handle this click event.
});
});
});
I think you are over thinking it a bit. You only need to worry about making it possible to load the script once the dom elements are ready. You could look at using something like require.js as well.

How do can I wire up an event to trigger after methods of my choosing finish execution in JavaScript?

Hard to summarize in one question, but here are the details:
I have an ASP.NET MVC 3 project (many of them actually).
My standard practice is for each view to have an Init() method that is fired when the document is ready. This is where I put all my UI code, like rendering buttons and accordions, etc.
I am using the trick to hide un-formatted html elements by setting the html tag to display: none and after Init() is complete, I can unhide everything.
This works pretty well, but I initially had the showing of content in my layout page, but that would execute before the Init code of a view finished running. It gets even more complex if I use partial views with their own Javascript.
What I would like is to attach a callback in one place that fires after the all of my possible Init() calls are finished.
I tried using custom events, but then I would have to trigger them at the end of every Init method, and that's not very efficient.
Requested Code:
Layout Page
<script>
$("html").addClass('init') // init has display: none
$(function() {
InitLayout() // Basic stuff for every page like menu, buttons, etc
$("html").removeClass('init'); // show all content
});
</script>
View Page
<script>
$(function() {
ViewInit() // Init all custom ui elements on page: tabs, accordions, etc
});
</script>
The problem is that the removeClass will occur before each page's Init fires. I am trying to find a way to avoid having the removeClass call at the bottom of every Init method. Is there some way to attach a callback programmatically to avoid repeating code. My main goal here is to implement hiding of unstyled content until everything is complete globally so I don't have to worry about it in each view.
You could try to register the occurence of the init procedure into a global variable (array). This should be done outside of the document.ready() or JQuery equivalent. So within the <script> tags.
When your Init functions, inside the document.ready() event handler or it's JQuery equivalent , are finished, unregister the occurence.
While unregistering, check if there are any occurences left, if not, modify your html style.
The gap between script parsing and the DOM actual finishes loading could be working for you in this case.

Categories