Using data-direction with dynamically loaded pages - jquery-mobile

I'm trying to load dynamic pages with jQuery, following this example.
(EDIT): Updated the code to provide a better view of the context
Here is a code sample
<div data-role="page" id="pageSample">
<div data-role="header">title</div>
<div data-role="content">
<a href="#home" data-role="button" data-transition="slide" data-direction='reverse'>Home</a>
</div>
<div data-role="footer">Footer</div>
</div>
$(document).bind( "pagebeforechange", function( e, data ) {
// Generate dynamic content of targeted pages...
$.mobile.changePage($(page), {
transition:"slide",
dataUrl:url,
reverse:reverse
});
});
The back button may be dynamically generated or not (such as this snippet). In both cases, it does not work reverse, as changePage is triggered through pagebeforechange.
Therefore, I inserted a reverse variable in changePage() options.
I can't find a way to retrieve the data-direction value of the clicked item.
I tried this just before changePage():
reverse = false;
$('a[data-direction="reverse"]').on("click", function(){
reverse = true;
});
But the reverse value is not updated in changePage(). I guess both codes run synchronously.
Is there a way to update the reverse value in changePage() ?

Final update
As per our discussion and your example http://jsfiddle.net/Iris/UZBhx/21/
Change this
$('a').on("click", function()
to
$(document).on("click", 'a', function()
Another update
Binding the $.mobile.changePage to pagebeforechange triggers all your code twice. Thus you lose the value of reverse or it gets neglected when the command executes the first time.
Try binding it to pagebeforehide as below.
$(document).bind( 'pagebeforehide', '[data-role="page"]#PageId', function( e, data ) {
// Generate dynamic content of targeted pages...
$.mobile.changePage($(page), {
transition:"slide",
dataUrl:url,
reverse:reverse
});
});
Update
To use reverse effect on specific buttons, you can follow this method.
First, assign a class for buttons with reverse effect, e.g. ui-reverse and add the below script.
$(document).on('click', '[data-role='button'].ui-reverse', function() {
$.mobile.changePage( url, {
transition:"slide",
reverse: true,
dataUrl:url
});
});
"Back" button links - Jquery Mobile
data-direction="reverse"
Is meant to simply run the backwards version of the transition that will run on that page change, while data-rel="back" makes the link functionally equivalent to the browser's back button and all the standard back button logic applies.
data-rel="back"
This will mimic the back button, going back one history entry and ignoring the anchor's default href.
Adding data-direction="reverse" to a link with data-rel="back" will not reverse the reversed page transition and produce the "normal" version of the transition.
In your case, you want to reverse transition, use the below code.
$.mobile.changePage($(page), {
transition:"slide",
reverse: true, // this will reverse the affect of the transition used in the page.
dataUrl:url
});
Read more about it here.

Related

changePage "jumps" back to old page

I've a big problem with a jQuery Mobile Application:
I'm using custom functions (they are triggered by onClick) to switch the page with currentPage.
It only happens on Android-Devices on sites in which has changed (due to ajax requests) with the integrated browser. iOS and Chrome works nice.
After clicking on an element, the animation started but just before it ends, it switches back to the old page. After a half second, it switches back to the new.
I made a movie of the bug here: http://www.youtube.com/watch?v=sXxvVUxniNg
Thank you very much
Code (CoffeeScript):
class Guide
#categoriesLoaded = false
#loadSearch: ->
$.mobile.changePage $("#guide"),
transition: 'slide'
changeHash: false
if !#categoriesLoaded
#categoriesLoaded = true
GuideApi.getCategories (data) ->
output = Mustache.render $("#tmpl-guide-categories-select").html(),
categories: data
$("#guide-search-category").append output
$("#guide-search-category").val($("#guide-search-category option:first").val());
window.WgSwitchGuide = ->
Guide.loadSearch
I was having the same issue. And I tried everything, I finally end with the solution. What I found was the error was principally within the browser. So I set the configuration of the pushStateEnabled as false. I did it by doing the following, adding this script.
<script type="text/javascript">
$(document).bind("mobileinit", function(){
$.mobile.pushStateEnabled = false;
});
</script>
It should be add before the jquery-mobile script is call, for more information you could see it on JQuery description
And it solved the problem no more jumping back.
I was having the exact same issue on both android and ios. For me, it was happening for heavy pages, i.e., pages with complex elements etc. Looks like you are using "slide" transition, which was what I was using as well. Taking out the page transitions (i.e., $.mobile.changePage("page.html", { transition: "none" })) for those pages resolved this issue for me. Hope this helps.
If you want to retain the transition, you can try preloading the page first when the previous page is being shown, by using the $.mobile.loadPage, and then show the transition. I am myself exploring this route, but it is probably worth trying.
Edit: OK - I explored the last suggestion and this doesn't seem to be working. Will stick with the first option.
Would you try to add the event stopPropagation and preventDefault methods on the first page's click event? This way the default action of the click event will not be triggered. Moreover the stopPropagation prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
event.stopPropagation();
event.preventDefault();
Example:
$("p").click(function(event){
event.stopPropagation();
event.preventDefault();
// change page
});
After trying for weeks to find a solution to this, I ended up doctoring the JQM library to disable page transitions one right after another. It's not a good solution, but it's the only thing I could get to work.
I was getting pages jumping back on both $.mobile.changePage and on anchor links. I used the slide transition, but removing it did not fix the problem. Setting pushStateEnabled to false did not work either. The jumps were happening on all devices and browsers (that I tested, anyway).
So here's what I did to the JQM library (v1.3.2).
Before the $.mobile.changePage function is defined, I added:
var justChangedPage = false;
Then within the function there's a line that goes:
if ( pbcEvent.isDefaultPrevented()) {
return;
}
which I changed to:
if ( pbcEvent.isDefaultPrevented() || justChangedPage) {
return;
}
Then right after this part of the $.mobile.changePage function:
if ( toPage[ 0 ] === $.mobile.firstPage[ 0 ] && !settings.dataUrl ) {
settings.dataUrl = documentUrl.hrefNoHash;
}
I added:
justChangedPage = true;
setTimeout(function() {
justChangedPage = false;
}, 500);
(Putting that earlier in the function didn't work -- all that stuff executes more than once within a single page transition. And half a second seemed to be the minimum timeout that prevented the page jumps.)
I hope this helps someone even if it is a hack...
What is your JQM and Android version?
I'm not sure If I understand correctly. I think transition flicker maybe come from the following assumption.
Heavy page DOM transition.
Using "translate3d" somewhere in css file.
Not using "H/W Acceleration" feature. Enable by add this line to your AndroidManifest.xml in <application>
android:hardwareAccelerated="true"
I encountered exactly the same behaviour and it seems that few people are having the same issue. At first I thought it is caused by jQuery mobile library. Later on, I manage to find where the problem came from and it is a bug in my own code.
I made a demo to explain the issue.
http://jsfiddle.net/pengyanb/6zvpgd4p/10/
Hopefully, this can be hint for people having the same problem.
$(document).on('pagebeforeshow', '#page2', function(){
console.log('Page2 before show');
var htmlGeneratedOnTheFly = '<ul data-role="listview" data-inset="true">';
for(var i=0; i<4; i++)
{
htmlGeneratedOnTheFly += '<li><a>Random html element</a></li><li data-role="list-divider"></li>';
}
htmlGeneratedOnTheFly += '</div>';
$('#page2UiContent').empty();
$('#page2UiContent').append(htmlGeneratedOnTheFly);
$('#page2UiContent').trigger('create');
//////////////////////////////////////////////////
//The following section is where the bug is generated.
//Each on "page2 before show event" will add a OK Button click handler.
//The handlers never get cleared.
//More and more handler is added to the Page2 OK button as pages going back and forth.
//Open the browser's console window to see multiple "Page 2 OK Button clicked!!!" lines on one button click.
//To fix the bug, move the following section out of the $(document).on('pagebeforeshow', '#page2', function(){});
//////////////////////////////////////////////////
$('#page2OkButton').click(function(){
console.log("Page 2 OK Button clicked!!!");
$.mobile.changePage('#page1', {transition:"flip"});
});
//////////////////////////////////////////////
//////////////////////////////////////////////
});
<link href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css" rel="stylesheet"/>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-role="page" id="page1" data-theme="a">
<div data-role="header" data-position="fixed">
<h5>Demo Page 1</h5>
</div>
<div data-role="main" class="ui-content">
<h2>jQuery mobile changepage jumps back to old page demo</h2>
<p>Click "Go To Page 2" button to go to page2</p>
<p>On Page2 click Ok Button to come back to page1</p>
<p>Keeping going back forth between two pages for few times.</p>
<p>Eventually, you will find that clicked on "Go To Page2" button to flip to Page2 but it soon jumps back to page1 automatically. </p>
<h2>Please read the comments in the javascript for explaination</h2>
Go To Page 2
</div>
</div>
<div data-role="page" id="page2" data-theme="a">
<div data-role="header" data-position="fixed">
<h5>Demo Page 2</h5>
</div>
<div id="page2UiContent" data-role="main" class="ui-content">
</div>
<div data-role="footer" data-position="fixed" style="text-align:center;">
<div data-role="navbar">
<ul>
<li><a id="page2OkButton" class="ui-btn ui-icon-check ui-btn-icon-left">OK</a></li>
</ul>
</div>
</div>
</div>

jQuery UI tabs: How do I load a specific element from a different page?

I have jQuery UI tabs set up, but a problem that I'm having with links to different pages is that they load all contents of the page into the tab. This includes the footer, header, and other navbars that I don't want in the tab. What if I would only like to load a single ID from that page?
My tabs are set up this way:
<div id="mytabs">
<ul>
<li>Awesome page</li>
<li>Foo</li>
</ul>
</div>
Nothing much going on in the jQuery...
$(function() {
$( "#mytabs" ).tabs();
});
Let's say this is the html of "awesomepage" (that the first link targets):
<html>
<head>
<title>awesome page</title>
</head>
<body>
<div id="header">bla</div>
<div id="awesomeness">awesomeness!</div>
<div id="footer">fdsfd</div>
</body>
</html>
...And I only want the tab to load #awesomeness from the page. How would I go about doing this? I've read into some guides that do that by adding a data-target="#youridhere" attribute to the HTML, but I'm still confused on how to implement the javascript. It seems like this is a convenient solution, as I won't be targeting the same ID in every page. Any clues on how to get the javascript working?
Thanks in advance!
The function that allow to load partial code of the response is the $.load() function.
Unfortunately, the tabs() feature does not use this function but use $.ajax instead.
You can try this solution:
You can try to stop the default processing on the beforeLoad callback and manage your ajax call with the $.load() method.
(base on the 1.9 documentation, you may should adapt)
$('#tabs').tabs({
// Callback run when selecting a tab
beforeLoad: function(event, ui) {
// If the panel is already populated do nothing
if (ui.panel.children().size() > 0)
return false;
// Make your own ajax load (with fragment feature)
ui.panel.load(ui.tab.attr('href') + ' #yourFragment');
// stop the default process (default ajax call should not be launched)
return false;
});
NOTICE: I'm not sure about extracting the URL with ui.tab.attr('href'), check before what object is ui.tab, but it should be easy to retrieve the href parameter.
Good luck
Got the solution :) Using one of the answers as a reference point, the tabs can now load a single element specified in the data-target attribute. Here is the modified version:
$(function() {
$('#tabs').tabs(
{
beforeLoad: function(event, ui) {
if (ui.panel.children().size() > 0)
return false;
ui.panel.load($('a', ui.tab).attr('href') + $('a', ui.tab).attr('data-target'));
return false;
}
});
});

jQuery Tab is caching TabID

I defined my jQuery tabs like this:
$('#serviceTabs').tabs({
idPrefix: 'ui-subtabs-',
spinner: 'Retrieving data...',
cache: false,
select: function(event, ui) {
if(checkServiceTabs(ui.index))
{
$('#ui-subtabs-'+(currentDetailTab+1)).html(" ");
currentDetailTab = ui.index;
return true;
}
else
return false;
},
collapsible: true
});
Unfortunately after reloading my page the index of my tabs is raised incrementally.
So on first request my TabID's look like:
#ui-subtabs-1, #ui-subtabs-2, #ui-subtabs-3
after reloading my page it looks like:
#ui-subtabs-4, #ui-subtabs-5, #ui-subtabs-6
The side effect is, that the tabs are locked after reload. The select event doesn't work anymore.
FYI: The tabs are in a DIV and merged with $.get function.
So i don't reload the whole page but only the div.
Before the new request I already blank the div with .html(" ") and I also tried
$('#serviceTabs').tabs("destroy");
Does anybody have an idea how to delete the TabID cache ?
Unfortunately, the tabIndex variable from which the TabID is coming from is encapsulated in the anonymous function of the Tabs plugin, making it totally invisible to the outside world. It is only incremented and the plugin offers no method to be able to reset it. Even destroying the instance of the plugin would not help.
On the overview page of the plugin's documentation though, it is specified that the tab containers can be references using the Title attribute of the <a> elements serving as tab buttons.
You would have then this kind of markup for the tab buttons:
<li> ... </li>
This will create tab containers with the title as ID (replacing spaces with underscores):
<div id="My_Tab_1"> ... </div>
You would have then to modify you select method accordingly.

Attach ui-widget to dynamic element

When dynamically creating a div using an .ajax() function. I'm unable to attach the .tabs() widget to the newly created .
This link creates the new div and pulls the #tabs div from "somefile.php"
Creates New Div
Here is the dynamically created div:
<div id="newdiv">
<div id="tabs">
<ul>
<li>Example One</li>
<li>Example Two</li>
</ul>
</div>
</div>
Here is the script I'm using. Output - Error: (d || "").split is not a function
Copy code
$( "#tabs" ).live(function(){
$(this).tabs()
});
I'm able to show the tabs when adding an event parameter, However I want the tabs to display without an event.
Copy code
$( "#tabs" ).live("click", function(){
$(this).tabs()
});
Someone please help me understand what I'm missing. I've been stuck on this for 3 days.
Chris
Are you trying to assign the live handler before the AJAX callback has completed?
My suspicion is you need to move your code into the success handler of your AJAX object and not use live because I don't think it does what you think.
If you post more of your code we'll be able to help you out a bit more.
My guess as to what you're trying to do:
$.ajax({
type: "GET",
url: "/tabs/",
async: true,
success: function() {
$('#tabs').tabs()
}
});
RSG is correct in that you're using the live function incorrectly. The live function is specifically for attaching event handlers to elements and calling functions. As RSG pointed out, in your case the best thing to do is call the tabs widget in the success function of the ajax request.

jQuery / jQuery UI - $("a").live("click", ...) not working for tabs

So I have some jQuery UI tabs. The source code is as follows:
HTML:
<div class="tabs">
<ul>
<li>Ranges</li>
<li>Collections</li>
<li>Designs</li>
</ul>
<div id="ranges"></div>
<div id="collections"></div>
<div id="designs"></div>
</div>
jQuery:
$(document).ready(function() {
$(".tabs").tabs();
});
My problem is that I am trying to make each tab load a page into the content panel on click of the relevant link. To start with I am just trying to set the html of all the panels on clicking a link. From the code below, if I use method 1, it works for all links. However if I use method 2 it doesn't - but only for the links in the tabs (i.e. the labels you click to select a tab).
Method 1 (works for all links all the time, but would not be applied to links which are added after this is called):
$("a").click(function () {
$("#ranges, #collections, #designs").html("clicked");
});
Method 2 (works for all links which are not "tabified"):
$("a").live("click", function () {
$("#ranges, #collections, #designs").html("clicked");
});
Does anyone know why it is behaving like this? I would really like to get method 2 working properly as there may well be links which I need to add click events to which are added after the page is originally loaded.
Thanks in advance,
Richard
PS yes the function calls for .live and .click are both in the $(document).ready() function, before anyone says that that may be the problem - otherwise it wouldn't work at all..
Edit:
The solution I came up with involves an extra attribute in the anchors (data-url) and the following code (which outputs a 404 not found error if the page cannot be loaded). I aim to expand this over the next few weeks / months to be a lot more powerful.
$(".tabs").tabs({
select: function (event, ui) {
$(ui.panel).load($(ui.tab).attr("data-url"), function (responseText, textStatus, XMLHttpRequest) {
switch (XMLHttpRequest.status) {
case 200: break;
case 404:
$(ui.panel).html("<p>The requested page (" + $(ui.tab).attr("data-url") + ") could not be found.</p>");
break;
default:
$(ui.panel).html("<p title='Status: " + XMLHttpRequest.status + "; " + XMLHttpRequest.statusText + "'>An unknown error has occurred.</p>");
break;
};
});
}
});
I don't know if I understand what you are going for but basically you want to do something once a tab is clicked?
Here's the docs for setting up a callback function for selecting a tab.
EDIT: Don't know if that link is working correctly, you want to look at select under Events. But basically it is:
$("#tabs").tabs({
select: function(event, ui) { ... }
});
Where ui has information on the tab that was clicked.
jQuery UI tabs has an outstanding issue where return false; is used instead of event.preventDefault();. This effectively prevents event bubbling which live depends on. This is scheduled to be fixed with jQuery UI 1.9 but in the meantime the best approach is use the built in select event as suggested by #rolfwaffle.
Maybe the tabs() plugin that you are using is calling event.preventDefault(); (Reference) once it has created it's tabs.
Then it captures the click event and the bubbling stops, so it doesn't invoke your click-function. In jQuery this is done with
$(element).click(function(){
// Do stuff, then
return false; // Cancels the event
});
You'd have to alter the tabs() plugin code and remove this return false; statement, OR if you are lucky, the plugin might have an option to disable that behavior.
EDIT: Now I see you're using jQuery UI. Then you should check the documentation there, since it is an awesome plugin, it will do anything you want if you do the html right and pass it the right options.

Resources