I have a simple function that opens a page with jquery mobile; the page structure is like that:
$(document).on('pageinit','#page', function(){
//all script
});
My function:
function dettail(id) {
//alert(id);
localStorage.setItem("id", id);
var url = "#page";
$.mobile.changePage( url, {transition: "none", reloadPage:true} );
}
This function doesn't load #page; "reloadPage:true" why doesn't work?
ps (I used pageinit and no pageshow because I need that the page is loading only in one case).
Try using the allowSamePageTransition option, i.e.:
$.mobile.changePage(
window.location.href,
{
allowSamePageTransition : true,
transition : 'none',
showLoadMsg : false,
reloadPage : true
}
);
Taken from http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/
If I understand your question correctly, you are trying to refresh just a specific #page portion within a multi page layout.
As you have discovered, the $.mobile.changePage does not work like that, it retrieves a fresh copy of the entire page from the server and not just the #page portion you want to refresh. The work around I came up with uses an 'emulated' refresh, for lack of a better term.
The following will walk you through the setup/use of the emulated refresh:
Step 1 - Create an empty page
Place the following html code into the body .. /body section of your multi page layout
<div data-role="page" id="empty_page_content" data-theme="b" data-content-theme="b"></div>
Step 2 - Your dettail() function
In the head .. /head section (or an external js file loaded in this section), BEFORE the jquery mobile library is loaded, place your dettail function, written as follows:
function dettail(id){
localStorage.setItem("id", id);
//emulate a refresh by switching to an empty page div (and then back to this page again)
$.mobile.changePage(
'#empty_page_content',
{
allowSamePageTransition : true,
transition : 'none',
showLoadMsg : false,
reloadPage : false
}
);
}
Step 3 - Setup a pageshow event on the #empty_page_content page
In the head ... /head section (or an external js file loaded in this section), BEFORE the jquery mobile library is loaded, place the following js code:
$(function() {
$(document).on("pageshow", "#empty_page_content", function() {
//console.log('pageshow event - #empty_page_content only');
// return to #page whenever this page is loaded
// The return url is hardcoded in this example but it could be switched to a variable if different return pages are needed
$.mobile.changePage(
'#page',
{
allowSamePageTransition : true,
transition : 'none',
showLoadMsg : false,
reloadPage : false
}
);
});
});
Step 4 - doing stuff in your #page each time it is displayed
In the head ... /head section (or an external js file loaded in this section), BEFORE the jquery mobile library is loaded, place the following js code:
$(function() {
$(document).on("pageshow", "#page", function() {
//console.log('pageshow event - #page');
// .. do stuff here, such as look for a stored id value and update the content of the #page accordingly
});
});
I successfully tested this solution on a private network (so I don't have a link for you to go look at). Hopefully it will work for you in your project. If not let me know and I'll see if I can help you get it going.
Just remember that it is best to load all head .. /head javascript code that is needed for all your pages on every page (best done by loading the same external js file on all pages) because the js code in the head section is only ever loaded ONCE from the first page that is accessed. You may intend for users to initially browse page1 but unless you can guarantee it your code should work if page 2 or 3 or etc were initially loaded instead.
reloadPage:true works only with page urls, not page ids
therefore:
$.mobile.changePage("#page", {
transition : "fade",
reverse : false,
changeHash : false,
allowSamePageTransition : true,
reloadPage:true
});
will not work
Related
i am working on a project which is based on jquery Mobile. i am a biggner in this field, so sorry for the silly question. the question is -- i have a page 'Page1' and i am using post method to fetch data from database. On success i am showing a notification to user through a notification dialog(without cancel and ok button). now what i want this success message on another page "page2", and the message should be there up to 2 sec and then disappear automatically. i have tried
function sendAddGuest(data, dialog) {
$.post("/GuestsList/AddGuest", data, function (response) { //using the post method
//alert(JSON.stringify(response));
$('.error').html("");
hideLoading();
if (response.result == 'success') { //if the process done
$.mobile.changePage('/GuestsList/Index', { dataUrl: "/GuestsList/Index", reloadPage: false, changeHash: true }); //To another page "page2"
// window.setTimeout('showToastMessage("Guest added successfully with window");',2000); //i have tried this
setTimeout(function () { showToastMessage("Guest added successfully test2"); }, 100); //and this also i want to show this message on other page "page2"
}
}
I am also beginning with Jquery Mobile, based in the toy project I am working with I would suggest the following:
Use popup from jquerymobile instead of showToast, then you could call
the .close() of the element in the settimeout function.
This is the div you create for your popup (you put it in the page 2):
<div data-role="popup" id="myPopup" class="ui-content" data-theme="e">
<p>Guest added successfully</p>
</div>
This is how you could call the function to open once in the new page (use the pageload event):
$('#myPopup').popup('open');
This is how you could call the function to close (in the same pageload event):
window.setTimeout(function(){ $('#myPopup').popup('close'); }, 2000)
Sorry I have no time to code a complete example, but I think this is the way to go.
Hope this helps!:-)
I'm developing a jquery mobile site that is only available to users that are logged in.
I have a function that checks a server for their logged in status:
function checkLogin() {
$(function () {
$.getJSON(root_url + 'manageUsers/checklogin/?callback=?', null,
function (data) {
if (data.logged == 'false') {
$("#index_Container").html("<h2>Login Required</h2></div><p>We've noticed you're not logged in, please login to use this app.</p><p><a href='login.html' data-role='button'>Click here to login</a></p>").trigger('create');
$.mobile.changePage('login.html');
} else {
$(".logged_in").text(data.username);
$(".logged_in").addClass('logout');
$(".header_div").trigger('create');
}
});
});
}
I can't seem to figure out how to implement this so everytime the index page is loaded and any other page loads this is fired prior to rendering anything else on the page. Currently, the page will load and show the HTML, then do $.mobile.changePage('login.html'):
EDIT: If anyone has any ideas on how to implement this in a better way I'd love to know, every page in the app requires the user to be logged in.
In order to have this function run every time you load anew page, you will need to bind it to the pagebeforeload event, and potentially cancel the user navigation if it does not validate the login.
$( document ).bind( "pagebeforeshow", function( event, data ){
event.preventDefault(); //prevents usual load of page
checkLogin(data);
});
You will have to make changes to checkLogin, notably because as the page does not exist yet, so you cannot make changes to the DOM. You can see an quick and dirty example in this fiddle, giving hints as to how do it considering the asynchronous nature of your call.
I didn't find an answer to my question anywhere and I know nothing about javascript, so I can't figure it out myself.
If I have jQuery mobile website built so that every single page is in separate html file (single page template). May I use standard asynchronous Google Analytics code with it, or do I have to make modifications similar to those used in multi page template?
Would be very thankful if someone could answer this question.
Yes, you can use the standard Google Analytics code. You will however, need to "push" certain page views to Google Analytics because of the way jQuery Mobile handles page navigation.
For example, if you have a Contact form on your site at contact.html that, once submitted, goes to a process.php page, and then after completing, the user arrives at thank-you.html, you will need to call some JavaScript to "push" the pageview to Google Analytics.
For example, if your jQuery Mobile page element (data-role="page") has id="thank-you", then I'd use this:
<script type="text/javascript">
$(document).delegate('#thank-you', 'pageshow', function () {
//Your code for each thank you page load here
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
_gaq.push(['_trackPageview', '/thank-you.html']);
});
</script>
UPDATE:
I would put this in your script.js file which is included in the head after you load jQuery and jQuery Mobile. This fires on each data-role="page" pageshow event, and is currently working on my live projects just fine.
$('[data-role=page]').live('pageshow', function (event, ui) {
try {
_gaq.push(['_setAccount', 'UA-XXXXXXX-X']);
hash = location.hash;
if (hash) {
_gaq.push(['_trackPageview', hash.substr(1)]);
} else {
_gaq.push(['_trackPageview']);
}
} catch(err) {
}
});
I have a few links on my site that will need to show a modal dialog when the user clicks on one of them. The modal will contain a message like: You are now leaving the "SECTION NAME" part of "SITE NAME". The user will then either accept which will allow the user to continue on with their request or cancel which will keep the user where they are.
An example of a link would be: My Interests
So as you can see the class of leaving-section would cause the link to do what I have specified above, and will also open the link in a new tab/window BUT the user must first accept that they are aware they are being taken to another part of the site.
I have looked at the docs but I haven't seen any examples where a) the dialog is created on the fly rather than hiding and showing a div and b) allowing the user to confirm and being sent to their original location i.e. the url which they clicked.
This is what I have so far:
$("#leaving-section").dialog({
resizable: false,
modal: true,
buttons: {
"I understand, take me there": function () {
$(this).dialog("close");
},
"I want to stay where I am": function () {
$(this).dialog("close");
}
}
});
$('.leaving-section').click(function (event)
{
event.preventDefault();
var $dialog = $('#leaving-section');
$dialog.dialog('open');
});
But I want to the modal to be created by jquery instead of the div being embedded in the page! Also how do I get the first button to send them off to their original destination?
Thanks to all who can help. Thanks
I just had to solve the same problem. The key to getting this to work was that the dialog must be partially initialized in the click event handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click. I used a CSS class to indicate which links should have the confirmation behavior.
Here's my solution, abstracted away to be suitable for an example.
<div id="dialog" title="Confirmation Required">
Are you sure about this?
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true
});
});
$(".confirmLink").click(function(e) {
e.preventDefault();
var targetUrl = $(this).attr("href");
$("#dialog").dialog({
buttons : {
"Confirm" : function() {
window.location.href = targetUrl;
},
"Cancel" : function() {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});
</script>
<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>
I believe that this would work for you, if you can generate your links with the CSS class (confirmLink, in my example).
I think this plugin may be help
http://jqueryui.com/demos/dialog/#modal-confirmation
Heres an example of how you can do it:
http://jsfiddle.net/yFkgR/3/
Or to do something besides cancel
http://jsfiddle.net/yFkgR/4/
You can just define your own buttons. You can style the dialog box anyway you want, i just used the default.
also to use ajax to load the html you can take a look at:
jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs
There is an open option you can use to load html from a remote web page. I jquery you can create a div just be doing
$("<div>");
it will create the closing tag too. Or as suggested in the post you can also use
$('a.ajax')
I have Page A which calls Page B using AJAX. Page B will be put in a div container in Page A. Within the result (which is Page B), there's a code that will initiate a jQuery UI Dialog. The div for the dialog is also in Page B. However, it doesn't work. I'd have to put the initiation code in Page A. So, if I want to put the initiation code in Page B, what should I do ?
The initiation code:
$('#dialog').dialog({
bgiframe: true,
autoOpen: false,
width: 300,
height: 300,
modal: true,
resizable: false,
buttons: {
'Create an account': function() { },
Cancel: function() { }
},
close: function() { }
});
I've also tried using $('div.dialog') as the selector (changed the id to class) and it does work, but everytime I request Page B (without reloading Page A), the dialog will multiply. For an example, the first time I requested Page B, one dialog will be opened. The second time I requested Page B, two dialogs will be opened.
Your approach isn't far off, you're just duplicating the dialog on the call when loading each time, so destroy the previous one, so instead of this:
$('div.dialog').dialog({ ...options... });
Call this:
$('div.dialog').dialog('destroy').dialog({ ...options... });
This prevents multiple dialogs from being instantiated for the same element. Alternatively, you can check if the dialog has been created on that element yet, like this:
$('div.dialog').filter(function() {
return $(this).closest('.ui-dialog').length === 0;
}).dialog({ ...options... });
This creates the dialog only on <div class="dialog"> elements that aren't already wrapped in a dialog.
You could do that using jQuery live function with custom event binding.
Everytime you make a call to Page B, you would have to trigger your custom event, so that the new dialog element can be binded in the event handler. The initiation code would have to be still in Page A if you follow this method.