Using JavaScript's history.pushState with Angular's $location.search() - javascript

Before I get into the long-winded explanation and the code, let me just say that I understand that my implementation of this system is a bit of a hack-job. The goal was to implement a linking feature on a SPA application without completely overhauling what was already done with Angular and the Bootstrap modals. I'll wager that I probably could have accomplished something better with directives, but my understanding of directives is lacking.
The following is a function that is launched when the system detects a change in the URL. The new URL parameters are passed and are used to query the back-end for content.
function handleUrlParamsModalLaunch(data) {
/*Ensure modal is not displaying any data*/
vm.modalData = {};
vm.selectedTab = null;
/*Show modal loading gif*/
vm.isModalLoading = true;
$("#contentPartModal").modal();
/*Call the content service to return the clicked content article*/
contentpartservice.getContentItem(data.id, data.type).then(function (contentItem) {
if (contentItem) {
vm.isModalLoading = false;
vm.modalData = contentItem;
return;
} else {
closeModal("#contentPartModal").then(function () {
vm.isModalLoading = false;
logger.error('An error occurred while fetching content');
});
return;
}
}, function (error) {
closeModal("#contentPartModal").then(function () {
vm.isModalLoading = false;
logger.error('An error occurred while fetching content');
});
return;
});
}
The following function is run when a link is clicked. It adds the parameters needed to retrieve content from the back-end to the URL.
function setUrl(contentId, contentType) {
var urlParams = $location.search();
if (urlParams.q) {
$location.search({ q: urlParams.q, type: contentType, id: contentId });
} else {
$location.search({ type: contentType, id: contentId });
}
return;
}
The following is where the solution starts to look like a hack job. I need to remove the parameters from the URL when the modal closes, but I couldn't find a way to catch the Bootstrap modal close event from the scope of my Angular controller (where the above functions are being called). Instead, I wrote the following JavaScript code in script tags that does it without Angular's $location dependency.
<script>
/*
* Detect the closing of a modal window and modify the URL to no longer display linking information.
* Not handled in Angular because Angular lacks a suitable way to detect a bootstrap modal close.
*/
$('#contentPartModal').on('hidden.bs.modal', function () {
var pageUrl = $.url();
var pageParams = pageUrl.param();
if (pageParams.q) {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?q=' + pageParams.q;
window.history.pushState({ path: newurl }, '', newurl);
}
} else {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname;
window.history.pushState({ path: newurl }, '', newurl);
}
}
});
</script>
Here is the resulting bug. The first time you click on a link, all of these functions run fine. The modal is opened with the correct data being displayed. When you close the modal, the URL parameters are removed from view. When you go to click on another link, the setUrl function is called, but the URL doesn't actually change. This results in the modal pop-up not opening. A second click on any link, and everything works as expected. The resulting bug is that each link needs to be clicked twice after the first time the modal has been opened.
Any hints to the cause of this bug would be much appreciated. I'd also accept an idea for a better implementation that would help me circumvent the issue altogether.
Thanks,
Matt

Related

Can't find storyboards using Ajax

Hey you all.
var $storyboards; // This is the wrapper were all stroy boards are.
// Listen to URL changes when clicking the back or forward buttons in the browser.
window.onpopstate = function(event) {
LoadPage(document.location.pathname, !history.state || stateCount > history.state.stateCount);
};
var stateCount = 0;
$( document).ready(function() {
$storyboards = $('#storyboards');
$('.storyboard').attr('data-url', location.pathname);
setTimeout(function(){
$('body').addClass('splash-screen-hidden');
}, 3000);
$(document).on('mouseover mouseout','#menu a', function(e){
$('#menu a').not(this).toggleClass('toggle');
}).on('click', '#menu a', function(e){
if(e.metaKey || e.ctrlKey) return;
// Listen to the click event on the a tags in the menu
// Prevent the default behavior so the browser doesn't load the page.
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
var title = $this.attr('title');
NavigateToPage(url, title);
})
});
function LoadPage(url, back){
var $all_storyboard = $('.storyboard'); // This is all the storyboards we have in the page.
var $storyboard = $all_storyboard.filter('[data-url="' + url + '"]');
var storyboard_exists = $storyboard.length > 0;
PreparePageForLoad();
if(storyboard_exists)
StoryboardIsLoaded($storyboard.hide());
else {
console.log("we do not have the storyboard.. go load it!");
$.ajax({
url: url,
success: function(data){
$storyboard = $('.storyboard', data);
$storyboard.attr('data-url', url);
$storyboards.append($storyboard);
StoryboardIsLoaded($storyboard.hide());
},
error: function(){
alert('Oops! We could not load this page!.');
GoToRoot();
}
})
}
}
I really have a huge problem since I have to deliver my website project tomorrow morning and right now it's not working very well.
The real problem is I'm having trouble with loading between my pages. I'm using storyboard and ajax to switch out the code/content in the HTML without making a page load. So I get these sweet smooth transition between my pages.
I tested it on my own server and domain and it all works fine, but because I have to deliver the project/folder on another server the shit won't work. The main reason is that I have to put it all in a folder on the server and it's messing up the root navigation.
When I click on the link it goes: http://websitename.com/html-document/
But it should be: http://websitename/myfolder/html-document/
So the problem is it's going out of my folder and looking for the HTML document outside my folder instead of looking at it.
Here is the link to the website: http://franklyone.com/sylvester-svend/
Thanks in advance - Love

Manipulating Browser History for AJAX loaded content

I have a page with navigation links on the left and a content div on the right. The navigation links HTML are set up like this.
Test
I have set up a JavaScript function as seen below that I thought would bind to the links, push a new state into the browser history and load the content for that link based on the data-mode value. Going FORWARD works perfectly, however when I go backward sometimes I have to click back twice to get go back to the previous hash and I'm not sure why.
Here is what I have so far.
<script language="javascript">
// Create var indicating the CURRENT mode we're on - home being the default when page loads
currentMode = "home";
// Push the default page (mode) into the history
history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + currentMode);
// bind to my nav links
$(document).on('click', '.nav-link', function(e){
e.preventDefault();
ajaxLoadVehicleSearchDetailContent($(this).data('mode'));
});
function ajaxLoadVehicleSearchDetailContent(mode) {
// Get the mode and link object
var thisMode = mode.toString().toLowerCase();
var thisLink = $('a[data-mode="' + mode + '"]');
// If we're switching to a different tab - continue
if (currentMode != thisMode) {
currentMode = thisMode;
// Get the content via AJAX
$.ajax({
url: "/myAjaxFunctionFileURL",
type: "POST",
data: { method:"getTabContent", mode:thisMode },
success: function(result) {
history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + thisMode);
// Update the content area - fadeOut,replace,fadeIn
$('#contentArea').fadeOut(globalAnimationDuration, function() {
$('#contentArea').html(result).fadeIn(globalAnimationDuration);
$('.nav-link').removeClass('current');
thisLink.addClass('current');
});
}
});
}
}
// Listen for the popstate and load correct content when user goes BACK in history
window.addEventListener("popstate", function() {
if (location.hash.indexOf("#!") != -1) {
var thisMode = location.hash.split("/").slice(-1)[0];
ajaxLoadVehicleSearchDetailContent(thisMode);
}
}, false);
</script>
The globalAnimationDuration var is simply a variable with a value of 500.
Could anyone shine some light onto why the strange behavior when going back? Or even a good example showing how to perform the task that I could follow and update my methods accordingly?
JSFiddle Here
Thank you!
I figured it out. Since I'm calling the same ajaxLoadVehicleSearchDetailContent on both forward and back navigation, it was adding items to the stack errorneously when clicking back. So it would pop the items from the stack, call the function which then re-added it to the stack unless it was the current tab.
My solution added an additional argument to my ajaxLoadVehicleSearchDetailContent() method as seen below.
function ajaxLoadVehicleSearchDetailContent(mode,backward) {
// Get the mode and link object
var thisMode = mode.toString().toLowerCase();
var thisLink = $('a[data-mode="' + mode + '"]');
// If we're switching to a different tab - continue
if (currentMode != thisMode) {
currentMode = thisMode;
// Get the content via AJAX
$.ajax({
url: "/myAjaxFunctionFileURL",
type: "POST",
data: { method:"getTabContent", mode:thisMode },
success: function(result) {
if (!backward) history.pushState(null, document.title, location.pathname + "#!/detail-mode/" + thisMode);
// Update the content area - fadeOut,replace,fadeIn
$('#contentArea').fadeOut(globalAnimationDuration, function() {
$('#contentArea').html(result).fadeIn(globalAnimationDuration);
$('.nav-link').removeClass('current');
thisLink.addClass('current');
});
}
});
}
}
Then when I call it from my nav link - send false, and when I call it from my popstate event I call true.

Fill TextBox with data on page load using javascript

I'm working with a Google-Extention which allows me to open a new tab containing a form. After the form gets filled out and saved, every time I open this tab again the form should be prefilled with the data saved earlier.
Here is how the data gets saved: WORKS!
function saveCheckoutData() {
var vName = document.getElementById('txbx_name').value;
chrome.storage.sync.set({'name': vName}, function() {
console.log(vName);
})
}
Here is how i get the data: WORKS!
function getdata() {
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
The code above gets called on button click and works perfectly!
But as soon I try to do this when the tab gets opened it doesn't work (the tab gets opened but there is nothing in the textbox): DOESN'T WORK!
function configAutofill(){
var newURL = "autofill_data.html";
chrome.tabs.create({ url: newURL });
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
Does some one have an Idea why these lines do not work when creating a new tab?
Many thanks in advance.
Here's a question for you.
After creating a new tab, you access document.getElementById. Yes, but which document?
In your case, it would be the page calling create - which is not the created page.
In your case, it seems like you're opening a page that's part of the extension. Then you should just include code in it that will run on load.
You may want to check document.readyState:
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', getdata);
} else {
getdata();
}
If you're trying to do this with a webpage, you'll need a content script. Again, those normally execute after DOM is parsed - so just call getdata() at top level.

ajax image viewer , back button and history - missing html and css

I am playing with jquery and js, trying to build an ajax overlay image viewer for a PHP website. With this code included at the bottom of the 'gallery page', the viewer opens and i can navigate with next and previous links inside the viewer. But the back button and the history is hard to understand. The browser often shows only the response of the ajax call, without the underlying page and css files, after some clicks back.
Perhaps somebody knows what is generally happening in such a case? I would like to understand why back sometimes results in a broken page, i.e. only the ajax response.
<script type="text/javascript">
$(document).ready(function() {
function loadOverlay(href) {
$.ajax({
url: href,
})
.done(function( data ) {
var theoverlay = $('#flvr_overlay');
theoverlay.html( data );
var zoompic = $('#zoompic');
zoompic.load(function() {
var nih = zoompic.prop('naturalHeight');
var photobox = $('#photobox');
if($(window).width() >= 750){
photobox.css('height',nih);
}
theoverlay.show();
$('body').css('overflow-y','hidden');
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 750) {
photobox.css('height','auto');
zoompic.removeClass('translatecenter');
}else{
photobox.css('height',nih);
zoompic.addClass('translatecenter');
}
});
});
});
return false;
}
var inithref = window.location.href;
$(window).on('popstate', function (e) {
if (e.originalEvent.state !== null) {
//load next/previous
loadOverlay(location.href);
} else {
//close overlay
$('#flvr_overlay').hide().empty();
$('body').css('overflow-y','scroll');
history.replaceState(null, inithref, inithref);
}
});
$(document).on('click', '.overlay', function () {
var href = $(this).attr('href');
history.pushState({}, href, href);
loadOverlay(href);
return false;
});
});
</script>
edit
clicking forward works:
/photos (normal page)
/photos/123 (overlay with '/photos' below)
/locations/x (normal page)
/photos/567 (overlay with '/locations/x' below)
clicking back gives me the broken view at point 2.
Do you need to prevent the default behaviour in your popstate to prevent the browser from actually navigating back to the previous page?
you have to manage it by own code.
You have a few options.
Use localstorage to remember the last query
Use cookies (but don't)
Use the hash as you tried with document.location.hash = "last search" to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible
Changing to document.location.hash = "latest search" didn't change anything.t.
This goes into the rest of the jQuery code:
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
Another solution is that use INPUT fields to preserved while using back button. So, I do like that :
My page contains an input hidden like that :
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});

Override "Error Loading Page" for network failure in js file

I have JQuery Mobile-1.0.js file.
// Load a page into the DOM.
$.mobile.loadPage = function (url, options) {
// This function uses deferred notifications to let callers
// know when the page is done loading, or if an error has occurred.
var deferred = $.Deferred(),
// The default loadPage options with overrides specified by
// the caller.
settings = $.extend({}, $.mobile.loadPage.defaults, options),
// The DOM element for the page after it has been loaded.
page = null,
// If the reloadPage option is true, and the page is already
// in the DOM, dupCachedPage will be set to the page element
// so that it can be removed after the new version of the
// page is loaded off the network.
dupCachedPage = null,
// determine the current base url
findBaseWithDefault = function () {
var closestBase = ($.mobile.activePage && getClosestBaseUrl($.mobile.activePage));
return closestBase || documentBase.hrefNoHash;
},
// The absolute version of the URL passed into the function. This
// version of the URL may contain dialog/subpage params in it.
absUrl = path.makeUrlAbsolute(url, findBaseWithDefault());
// If the caller provided data, and we're using "get" request,
// append the data to the URL.
if (settings.data && settings.type === "get") {
absUrl = path.addSearchParams(absUrl, settings.data);
settings.data = undefined;
}
// If the caller is using a "post" request, reloadPage must be true
if (settings.data && settings.type === "post") {
settings.reloadPage = true;
}
// The absolute version of the URL minus any dialog/subpage params.
// In otherwords the real URL of the page to be loaded.
var fileUrl = path.getFilePath(absUrl),
// The version of the Url actually stored in the data-url attribute of
// the page. For embedded pages, it is just the id of the page. For pages
// within the same domain as the document base, it is the site relative
// path. For cross-domain pages (Phone Gap only) the entire absolute Url
// used to load the page.
dataUrl = path.convertUrlToDataUrl(absUrl);
// Make sure we have a pageContainer to work with.
settings.pageContainer = settings.pageContainer || $.mobile.pageContainer;
// Check to see if the page already exists in the DOM.
page = settings.pageContainer.children(":jqmData(url='" + dataUrl + "')");
// If we failed to find the page, check to see if the url is a
// reference to an embedded page. If so, it may have been dynamically
// injected by a developer, in which case it would be lacking a data-url
// attribute and in need of enhancement.
if (page.length === 0 && dataUrl && !path.isPath(dataUrl)) {
page = settings.pageContainer.children("#" + dataUrl)
.attr("data-" + $.mobile.ns + "url", dataUrl);
}
// If we failed to find a page in the DOM, check the URL to see if it
// refers to the first page in the application. If it isn't a reference
// to the first page and refers to non-existent embedded page, error out.
if (page.length === 0) {
if ($.mobile.firstPage && path.isFirstPageUrl(fileUrl)) {
// Check to make sure our cached-first-page is actually
// in the DOM. Some user deployed apps are pruning the first
// page from the DOM for various reasons, we check for this
// case here because we don't want a first-page with an id
// falling through to the non-existent embedded page error
// case. If the first-page is not in the DOM, then we let
// things fall through to the ajax loading code below so
// that it gets reloaded.
if ($.mobile.firstPage.parent().length) {
page = $($.mobile.firstPage);
}
} else if (path.isEmbeddedPage(fileUrl)) {
deferred.reject(absUrl, options);
return deferred.promise();
}
}
// Reset base to the default document base.
if (base) {
base.reset();
}
// If the page we are interested in is already in the DOM,
// and the caller did not indicate that we should force a
// reload of the file, we are done. Otherwise, track the
// existing page as a duplicated.
if (page.length) {
if (!settings.reloadPage) {
enhancePage(page, settings.role);
deferred.resolve(absUrl, options, page);
return deferred.promise();
}
dupCachedPage = page;
}
var mpc = settings.pageContainer,
pblEvent = new $.Event("pagebeforeload"),
triggerData = { url: url, absUrl: absUrl, dataUrl: dataUrl, deferred: deferred, options: settings };
// Let listeners know we're about to load a page.
mpc.trigger(pblEvent, triggerData);
// If the default behavior is prevented, stop here!
if (pblEvent.isDefaultPrevented()) {
return deferred.promise();
}
if (settings.showLoadMsg) {
// This configurable timeout allows cached pages a brief delay to load without showing a message
var loadMsgDelay = setTimeout(function () {
$.mobile.showPageLoadingMsg();
}, settings.loadMsgDelay),
// Shared logic for clearing timeout and removing message.
hideMsg = function () {
// Stop message show timer
clearTimeout(loadMsgDelay);
// Hide loading message
$.mobile.hidePageLoadingMsg();
};
}
if (!($.mobile.allowCrossDomainPages || path.isSameDomain(documentUrl, absUrl))) {
deferred.reject(absUrl, options);
} else {
// Load the new page.
$.ajax({
url: fileUrl,
type: settings.type,
data: settings.data,
dataType: "html",
success: function (html, textStatus, xhr) {
//pre-parse html to check for a data-url,
//use it as the new fileUrl, base path, etc
var all = $("<div></div>"),
//page title regexp
newPageTitle = html.match(/<title[^>]*>([^<]*)/) && RegExp.$1,
// TODO handle dialogs again
pageElemRegex = new RegExp("(<[^>]+\\bdata-" + $.mobile.ns + "role=[\"']?page[\"']?[^>]*>)"),
dataUrlRegex = new RegExp("\\bdata-" + $.mobile.ns + "url=[\"']?([^\"'>]*)[\"']?");
// data-url must be provided for the base tag so resource requests can be directed to the
// correct url. loading into a temprorary element makes these requests immediately
if (pageElemRegex.test(html)
&& RegExp.$1
&& dataUrlRegex.test(RegExp.$1)
&& RegExp.$1) {
url = fileUrl = path.getFilePath(RegExp.$1);
}
if (base) {
base.set(fileUrl);
}
//workaround to allow scripts to execute when included in page divs
all.get(0).innerHTML = html;
page = all.find(":jqmData(role='page'), :jqmData(role='dialog')").first();
//if page elem couldn't be found, create one and insert the body element's contents
if (!page.length) {
page = $("<div data-" + $.mobile.ns + "role='page'>" + html.split(/<\/?body[^>]*>/gmi)[1] + "</div>");
}
if (newPageTitle && !page.jqmData("title")) {
if (~newPageTitle.indexOf("&")) {
newPageTitle = $("<div>" + newPageTitle + "</div>").text();
}
page.jqmData("title", newPageTitle);
}
//rewrite src and href attrs to use a base url
if (!$.support.dynamicBaseTag) {
var newPath = path.get(fileUrl);
page.find("[src], link[href], a[rel='external'], :jqmData(ajax='false'), a[target]").each(function () {
var thisAttr = $(this).is('[href]') ? 'href' :
$(this).is('[src]') ? 'src' : 'action',
thisUrl = $(this).attr(thisAttr);
// XXX_jblas: We need to fix this so that it removes the document
// base URL, and then prepends with the new page URL.
//if full path exists and is same, chop it - helps IE out
thisUrl = thisUrl.replace(location.protocol + '//' + location.host + location.pathname, '');
if (!/^(\w+:|#|\/)/.test(thisUrl)) {
$(this).attr(thisAttr, newPath + thisUrl);
}
});
}
//append to page and enhance
// TODO taging a page with external to make sure that embedded pages aren't removed
// by the various page handling code is bad. Having page handling code in many
// places is bad. Solutions post 1.0
page
.attr("data-" + $.mobile.ns + "url", path.convertUrlToDataUrl(fileUrl))
.attr("data-" + $.mobile.ns + "external-page", true)
.appendTo(settings.pageContainer);
// wait for page creation to leverage options defined on widget
page.one('pagecreate', $.mobile._bindPageRemove);
enhancePage(page, settings.role);
// Enhancing the page may result in new dialogs/sub pages being inserted
// into the DOM. If the original absUrl refers to a sub-page, that is the
// real page we are interested in.
if (absUrl.indexOf("&" + $.mobile.subPageUrlKey) > -1) {
page = settings.pageContainer.children(":jqmData(url='" + dataUrl + "')");
}
//bind pageHide to removePage after it's hidden, if the page options specify to do so
// Remove loading message.
if (settings.showLoadMsg) {
hideMsg();
}
// Add the page reference and xhr to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.page = page;
// Let listeners know the page loaded successfully.
settings.pageContainer.trigger("pageload", triggerData);
deferred.resolve(absUrl, options, page, dupCachedPage);
},
error: function (xhr, textStatus, errorThrown) {
//set base back to current path
if (base) {
base.set(path.get());
}
// Add error info to our triggerData.
triggerData.xhr = xhr;
triggerData.textStatus = textStatus;
triggerData.errorThrown = errorThrown;
var plfEvent = new $.Event("pageloadfailed");
// Let listeners know the page load failed.
settings.pageContainer.trigger(plfEvent, triggerData);
// If the default behavior is prevented, stop here!
// Note that it is the responsibility of the listener/handler
// that called preventDefault(), to resolve/reject the
// deferred object within the triggerData.
if (plfEvent.isDefaultPrevented()) {
return;
}
// Remove loading message.
if (settings.showLoadMsg) {
// Remove loading message.
hideMsg();
//show error message
$("<div class='ui-loader ui-overlay-shadow ui-body-e ui-corner-all'><h1>" + $.mobile.pageLoadErrorMessage + "</h1></div>")
.css({ "display": "block", "opacity": 0.96, "top": $window.scrollTop() + 100 })
.appendTo(settings.pageContainer)
.delay(800)
.fadeOut(400, function () {
$(this).remove();
});
}
deferred.reject(absUrl, options);
}
});
}
return deferred.promise();
};
This is the code for showing an error message "Error Loading Page" for error in page. Here i want to show alert message for net connection failure as "Please check your net connection" instead of the below image.
Note: I dont want to change the pageloaderrormessage. want to stop to get the page error messages, instead of that i will enable my network error condition as in Show Network Error in android. If the user pressed "Ok" in alert dialog i'll navigate them into Reload.html.
Please tell me where i can check that condition and where i have to change the error message?
As both #shkschneider and #codemonkey have suggested you need to set this option on mobileinit
Example:
$(document).bind("mobileinit", function(){
$.mobile.pageLoadErrorMessage = "Please check your net connection";
});
Linking the jQM 1.0.1 docs:
http://jquerymobile.com/demos/1.0.1/docs/api/globalconfig.html
Here is a example:
http://jquerymobile.com/demos/1.0.1/docs/config/pageLoadErrorMessage.html ( click the "or Try this broken link" button )
Now if you have the ability to upgrade jQM to 1.1.1 you might try something like this:
//use theme swatch "b", a custom message, and no spinner
$.mobile.showPageLoadingMsg("b", "Please check your net connection", true);
// hide after delay
setTimeout( $.mobile.hidePageLoadingMsg, 1500 );
Docs:
http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
UPDATE:
Another thought is to use a plugin to achieve something like you want, Does something like this work?
http://dev.jtsage.com/jQM-SimpleDialog/demos/bool.html
Simply use:
$(document).bind("mobileinit", function(){
$.mobile.pageLoadErrorMessage("Please check your netconnection");
});
http://jquerymobile.com/test/docs/api/globalconfig.html
Set the pageLoadErrorMessage as described here http://jquerymobile.com/demos/1.1.1/docs/api/globalconfig.html
EDIT
If you want to handle the behaviour in a custom way, set loadingMessage to false. This prevents the loading message from being displayed. You can bind to the pageloadfailed (described here http://jquerymobile.com/demos/1.1.1/docs/api/events.html) and add add your custom handling logic in the event handler.

Categories

Resources