Navbar content loading all options - jquery-mobile

I have a navbar in Jquery mobile which have 5 contents, each content have a text right now. The problem is that the first time that I load the page, in the first tab all the content is loaded, and as soon as you start pressing the buttons, the content is loaded normally, as shown in the image below:
Then when I start clicking the buttons the content shows correctly:
Below is the code that I'm using:
Javascript:
<script>
(function($) {
// Before handling a page change...
$(document).bind("pagebeforechange", function(e, data)
{
// If the new page is not being loaded by URL, bail
if (typeof data.toPage !== "string")
{
return;
}
// If the new page has a corresponding navbar link, activate its content div
var url = $.mobile.path.parseUrl(data.toPage);
var $a = $("div[data-role='navbar'] a[href='" + url.hash + "']");
if ($a.length)
{
// Suppress normal page change handling since we're handling it here for this case
e.preventDefault();
}
// If the new page has a navbar, activate the content div for its active item
else
{
$a = $(url.hash + " div[data-role='navbar']").find("a.ui-btn-active");
// Allow normal page change handling to continue in this case so the new page finishes rendering
}
// Show the content div to be activated and hide other content divs for this page
var $content = $($a.attr("href"));
$content.siblings().hide();
$content.show();
});
})(jQuery);
Here is the HTML:
<body>
<div data-role="page">
<div data-role="header">
<div data-role="navbar">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
</div>
<center>
<div data-role="content">
<div id="oneContent">First</div>
<div id="twoContent">Second</div>
<div id="threeContent">Third</div>
<div id="fourContent">Fourth</div>
<div id="fiveContent">Fifth</div>
</div>
</center>
</div>
</body>
How can avoid the problem of loading all content at first load?

UPDATED TO ANSWER NEW REQUEST BELOW
If you want the first tab to show up by default, set the CSS of them all individually then toggle them into view.
First put this in your <head> or in a linked CSS file:
<style>[data-role=content] > div { display: none; }</style>
Then insert these two lines into your Javascript at the beginning like so:
(function ($) {
$(document).ready(function() {
var path = (window.location.hash) ? window.location.hash : '#oneContent';
$(path).show();
});
$(document).bind("pagebeforechange", function (e, data) {
....
Here's an updated fiddle diddle skittle

Related

Header back button with forced refreshing

I needed to force refreshing using this technique. When I navigate to a new page jQM correctly adds a back button in my header. But when I go back to the first page the back button incorrectly appears. Is it possible to conditionally create a back button? I have tried manually creating a back button and conditionally hiding it based on a parameter in the URI but it seems that once the button appears I can never hide it again.
Edit:
Here is some code that demonstrates the problem. Not only does it not hide the custom back button when you go back to page 1, but it doesn't hide the "page 1" content when you are on page 2, or visa versa. It seems that once something has been shown it cannot be rehidden.
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<script>
var backButtonVar = null;
var page1Var = null;
var page2Var = null;
</script>
</head>
<body>
<div data-role="page" data-add-back-btn="false">
<div data-role="header">
<h1>Test</h1>
<a id="backButton" data-role="button" data-direction="reverse" data-rel="back" data-icon="arrow-l" data-iconpos="left">MyBack</a>
</div>
<div id="page1" data-role="content">
Go to page 2
</div>
<div id="page2" data-role"content">
This is page 2
</div>
<script>
$(document).ready(function() {
jQuery(document).on('pagehide', 'div', function(event, ui) {
var page = jQuery(event.target);
page.remove();
});
backButtonVar = $('#backButton');
page1Var = $('#page1');
page2Var = $('#page2');
// Is this the root?
if (window.location.search == '') {
backButtonVar.hide();
page1Var.show()
page2Var.hide()
} else {
backButtonVar.show();
page1Var.hide()
page2Var.show()
}
});
</script>
</div>
</body>
</html>
Here is the fix. Give the back-button a class backButton. .hide() it if the active page is the home page page1, else .show() it.
Demo
$('.backButton').hide();
$(document).on('pagebeforeshow', function () {
var activePage = $.mobile.activePage;
if (activePage[0].id != 'page1') {
$('.backButton').show();
}
else {
$('.backButton').hide();
}
});
If you have any question, please let me know.

jquery load() will only load the html from the extermal page, no stylesheet or jquery ui

I have two pages. For explanations sake I'll call them page A and Page B. When I open page B in my browser it is rendered with all the styling and jquery ui code working properly, but when I open page B inside of a div in Page A via the load() method, the only thing that renders is the raw html, no styling, no interfaces. What is the problem? Directly below is the code from page B and all the way at the bottom is the code from page A:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> //jquery ui
<link rel="stylesheet" href="http://spilot.koding.com/lbStyle.css"/> //stylesheet
<script src="http://www.parsecdn.com/js/parse-1.2.2.min.js"></script> //parse database
<script>
$(function(){
var crowd = ' ';
var ageGroup = ' ';
var activity = [];
var scene = [];
var neighborhood = [];
var date = [];
var details = [];
var time = [];
Parse.initialize("ivHLAO7z9ml1bBglUNuPSgcWabXe3UeE2yCgKM2x","gNeGt04lU7xcew893EvbEJ05qqc4POVhBsIBSCVj");
$(".menu").menu({
select: function (event, ui) {
$('.selected', this).removeClass('selected');
var selection = ui.item.addClass('selected').children('a').attr('name'); //add background color to selected menu item and get its attribute name
var choice = ui.item.text(); //get text of menu selection
if(selection == "ageGroup"){
$("#ageGroup").text(choice); //change the text in the first <a> of ageGroup menu to ageGroup selection.
ageGroup = $("#ageGroup").text();
}else{
crowd = selection;
};
} // closes select function
}); // closes menu
$("button").click(function(){
var city = JSON.parse( localStorage.getItem('city') );
var niche = Parse.Object.extend(crowd);
var query = new Parse.Query(niche);
query.equalTo("ageGroup", ageGroup);
query.equalTo("city", city);
//query.include([activity.date.details.location.neighborhood.time])
query.find({
success: function(results) {
for (i = 0; i < results.length; i++){
activity = results[i].get("activity");
scene = results[i].get("location");
neighborhood = results[i].get("neighborhood");
date = results[i].get("date");
details = results[i].get("details");
time = results[i].get("time");
};
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
//alert("working");
}); //closes click()
}); // close function()
</script>
<script>
$(function(){
$( "button" ).button();
});
</script>
</head>
<body>
<div id="div1">
<button>Button label</button>
<div id="div2">
<ul class="menu">
<li>
Age Group
<ul>
<li>18-21</li>
<li>21-30</li>
<li>30-40</li>
<li>40-50</li>
<li>50-60</li>
<li>60-70</li>
<li>70-80</li>
<li>80-90</li>
<li>90-100</li>
</ul>
</li>
</ul>
</div>
<div id="div3">
<ul class="menu" id="menu">
<li><img src="" alt="" /><h2>Academic: Art Studies</h2></li>
<li><img src="" alt="" /><h2>Academic: Literature</h2></li>
<li><img src="" alt="" /><h2>Academic: Social Sciences</h2></li>
<li><img src="" alt="" /><h2>Academic: Physical/Natural Sciences</h2></li>
</ul>
</div>
</div>
</body>
</html>
--------------//PAGE A//--------------
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(function(){
$("#mainDiv").load("http://myURl.com/find2.html"); //this is where I call load()
});
</script>
</head>
<body>
//this is the div where I want the other page to load
<div id="mainDiv">
</div>
</body>
</html>
since you are loading page "b" into page "a", you need to have all page "b" stylesheets/js in page "a" header.
please note that you are loading a complete html page into page "a", that includes html,header,body and that is not desirable, you should make page "b" a template that only contains the markup you need.
UPDATE:
you are embedding your scripts in the html, that is a bad practice, separate the JS code to different files.
When you include JS code in your file it will run as soon as the page loads, so if you put 'pageb' code in 'pagea' it will run as soon as 'pagea' was loaded and when you load 'pageb' the code will not run again.
You need to put 'pageb' code in a function and call it only after you loaded 'pageb' content.

backbone view passed to jQuery Mobile

I've been trying to use backbonejs and jqm together.
I can render the main page alright. The page has a list that the user can tap on. The item selected should show a detail page with info on the list item selected. The detail page is a backbone view with a template that's rendered in the item's view object.
The detail's view .render() produces the html ok and I set the html of the div tag of the main page to the rendered item's detail markup. It looks like this:
podClicked: function (event) {
console.log("PodListItemView: got click from:" + event.target.innerHTML + " id:" + (this.model.get("id") ? this.model.get("id") : "no id assigned") + "\n\t CID:" + this.model.cid);
var detailView = new PodDetailView({ model: this.model });
detailView.render();
},
The detail view's render looks like this:
render: function () {
this.$el.html(this.template({ podId: this.model.get("podId"), isAbout_Name: this.model.get("isAbout_Name"), happenedOn: this.model.get("happenedOn") }));
var appPageHtml = $(app.el).html($(this.el));
$.mobile.changePage(""); // <-- vague stab in the dark to try to get JQM to do something. I've also tried $.mobile.changePage(appPageHtml).
console.log("PodDetailView: render");
return this;
}
I can see that the detail's view has been rendered on the page by checking Chrome's dev tools html editor but it's not displaying on the page. All I see is a blank page.
I've tried $.mobile.changePage() but, without an URL it throws an error.
How do I get JQM to apply it's class tags to the rendered html?
the HTML and templates look like this:
<!-- Main Page -->
<div id="lessa-app" class="meditator-image" data-role="page"></div>
<!-- The rest are templates processed through underscore -->
<script id="app-main-template" type="text/template">
<div data-role="header">
<h1>#ViewBag.Title</h1>
</div>
<!-- /header -->
<div id="main-content" data-role="content">
<div id="pod-list" data-theme="a">
<ul data-role="listview" >
</ul>
</div>
</div>
<div id="main-footer" data-role='footer'>
<div id="newPod" class="ez-icon-plus"></div>
</div>
</script>
<script id="poditem-template" type="text/template">
<span class="pod-listitem"><%= isAbout_Name %></span> <span class='pod-listitem ui-li-aside'><%= happenedOn %></span> <span class='pod-listitem ui-li-count'>5</span>
</script>
<script id="page-pod-detail-template" type="text/template">
<div data-role="header">
<h1>Pod Details</h1>
</div>
<div data-role="content">
<div id='podDetailForm'>
<fieldset data-role="fieldcontain">
<legend>PodDto</legend>
<label for="happenedOn">This was on:</label>
<input type="date" name="name" id="happenedOn" value="<%= happenedOn %>" />
</fieldset>
</div>
<button id="backToList" data-inline="false">Back to list</button>
</div>
<div data-role='footer'></div>
</script>
Thanks in advance for any advice... is this even doable?
I've finally found a way to do this. My original code has several impediments to the success of this process.
The first thing to do is to intercept jquerymobile's (v.1.2.0) changePage event like this:
(I've adapted the outline from jqm's docs and left in the helpful comments: see http://jquerymobile.com/demos/1.2.0/docs/pages/page-dynamic.html
)
$(document).bind("pagebeforechange", function (e, data) {
// We only want to handle changePage() calls where the caller is
// asking us to load a page by URL.
if (typeof data.toPage === "string") {
// We are being asked to load a page by URL, but we only
// want to handle URLs that request the data for a specific
// category.
var u = $.mobile.path.parseUrl(data.toPage),
re = /^#/;
// don't intercept urls to the main page allow them to be managed by JQM
if (u.hash != "#lessa-app" && u.hash.search(re) !== -1) {
// We're being asked to display the items for a specific category.
// Call our internal method that builds the content for the category
// on the fly based on our in-memory category data structure.
showItemDetail(u, data.options); // <--- handle backbone view.render calls in this function
// Make sure to tell changePage() we've handled this call so it doesn't
// have to do anything.
e.preventDefault();
}
}
});
The changePage() call is made in the item's list backbone view events declaration which passes to the podClicked method as follows:
var PodListItemView = Backbone.View.extend({
tagName: 'li', // name of (orphan) root tag in this.el
attributes: { 'class': 'pod-listitem' },
// Caches the templates for the view
listTemplate: _.template($('#poditem-template').html()),
events: {
"click .pod-listitem": "podClicked"
},
initialize: function () {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
render: function () {
this.$el.html(this.listTemplate({ podId: this.model.get("podId"), isAbout_Name: this.model.get("isAbout_Name"), happenedOn: this.model.get("happenedOn") }));
return this;
},
podClicked: function (event) {
$.mobile.changePage("#pod-detail-page?CID='" + this.model.cid + "'");
},
clear: function () {
this.model.clear();
}
});
In the 'showItemDetail' function the query portion of the url is parsed for the CID of the item's backbone model. Again I've adapted the code provided in the jquerymobile.com's link shown above.
Qestion: I have still figuring out whether it's better to have the code in showItemDetail() be inside the view's render() method. Having a defined function seems to detract from backbone's architecture model. On the other hand, having the render() function know about calling JQM changePage seems to violate the principle of 'separation of concerns'. Can anyone provide some insight and guidance?
// the passed url looks like #pod-detail-page?CID='c2'
function showItemDetail(urlObj, options) {
// Get the object that represents the item selected from the url
var pageSelector = urlObj.hash.replace(/\?.*$/, "");
var podCid = urlObj.hash.replace(/^.*\?CID=/, "").replace(/'/g, "");
var $page = $(pageSelector),
// Get the header for the page.
$header = $page.children(":jqmData(role=header)"),
// Get the content area element for the page.
$content = $page.children(":jqmData(role=content)");
// The markup we are going to inject into the content area of the page.
// retrieve the selected pod from the podList by Cid
var selectedPod = podList.getByCid(podCid);
// Find the h1 element in our header and inject the name of the item into it
var headerText = selectedPod.get("isAbout_Name");
$header.html("h1").html(headerText);
// Inject the item info into the content element
var view = new PodDetailView({ model: selectedPod });
var viewElHtml = view.render().$el.html();
$content.html(viewElHtml);
$page.page();
// Enhance the listview we just injected.
var fieldContain = $content.find(":jqmData(role=listview)");
fieldContain.listview();
// We don't want the data-url of the page we just modified
// to be the url that shows up in the browser's location field,
// so set the dataUrl option to the URL for the category
// we just loaded.
options.dataUrl = urlObj.href;
// Now call changePage() and tell it to switch to
// the page we just modified.
$.mobile.changePage($page, options);
}
So the above provides the event plumbing.
The other problem I had was that the page was not set up correctly. It's better to put the page framework in the main html and not put it in an underscore template to be rendered at a later time. I presume that avoids issues where the html is not present when jqm takes over.
<!-- Main Page -->
<div id="lessa-app" data-role="page">
<div data-role="header">
<h1></h1>
</div>
<!-- /header -->
<div id="main-content" data-role="content">
<div id="pod-list" data-theme="a">
<ul data-role="listview">
</ul>
</div>
</div>
<div id="main-footer" data-role='footer'>
<div id="main-newPod" class="ez-icon-plus"></div>
</div>
</div>
<!-- detail page -->
<div id="pod-detail-page" data-role="page">
<div data-role="header">
<h1></h1>
</div>
<div id="detail-content" data-role="content">
<div id="pod-detail" data-theme="a">
</div>
</div>
<div id="detail-footer" data-role='footer'>
back
</div>
</div>

Jquery tab re-addition

I am trying to add undo/redo functionality in Jquery tabs. I am able to store and restore li/divs for added/removed tab.
Issue is when I re-add tab to the form, though it is added properly as li and div for that particular tab are present and can be seen. But if I click on that tab 'tabsselect' event is not getting fired. Li and div for tab look in order. But I am not able to figure what is missing.
In my website I am dynamically adding and removing tabs and it is working fine but just readding of once removed tab isnt working
Here is the code for adding tab
var $tabs = $("#tabs").tabs({
tabTemplate: "<li><a href='#{href}'>#{label}</a> <span id='id1' class='ui-icon ui-icon-close'>Remove Tab</span></li>",
add: function (event, ui) {
var tab_content = $tab_content_input.val(); // || "Tab " + tab_counter + " content.";
}
});
Here is the removal code
$("#tabs span.ui-icon-close").live("click", function () {
if (imode == 1) {
var index = $("li", $tabs).index($(this).parent());
if ($tabs.tabs("length") > 1) {
$tabs.tabs("remove", index);
}
}
});
Nothing fancy really. Looking for answers.
Thanks
Try This code out this will give you a nice example to manipulate data in tabs using jquery.
JavaScript
$(document).ready(function(){
var $tabs = $('#tabs').tabs();
var $a = $('<a />').appendTo('body').attr('href','#').html('add new tab').click(function(){
var n = parseInt($tabs.tabs( "length" ),10)+1;
$('body').append('<div id="tabs-'+n+'">content for the tab # '+ n +'</div>');
$tabs.tabs("add",'#tabs-'+n,'Tab #'+n);
return false;
});
$('<a/>').html('<br><br>remove tab').attr('href','#').click(function(){
$tabs.tabs('remove',$tabs.tabs('length')-1);
return false;
}).appendTo('body');
});
HTML
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"></link>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
</style>
</head>
<body>
<div id="tabs">
<ul>
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
</ul>
<div id="tabs-1">
<p>Tab 1 content</p>
</div>
<div id="tabs-2">
<p>Tab 2 content</p>
</div>
<div id="tabs-3">
<p>Tab 3 content</p>
</div>
</div>
</body>
</html>
*
Just use the id's of the selected tabs and manipulate data in them. this will allow to add and remove tabs on your page
*
Tab Select Function
$('.ui-tabs-nav').bind('tabsselect', function(event, ui) {
ui.options // options used to intialize this widget
ui.tab // anchor element of the selected (clicked) tab
ui.panel // element, that contains the contents of the selected (clicked) tab
ui.index // zero-based index of the selected (clicked) tab
});
Use ui.index to get the index of the selected tab and then add then manipulate the selected tab .

Show feedback to a user when loading content though ajax

I'm using the jquery tab plugin with the same results that are on jquery ui site (link text).
The problem is that I want to change the tab label to something like "Loading" when the Ajax request is waiting for a response. How shall I achieve that?
Edit:
What I have now:
<div id="tabs">
<ul>
<li>User Profile</li>
<li>Edit</li>
<li>Delete AccountT</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("UserProfile", Model); %>
</div>
</div>
and on javascript I just have the following code:
<script type="text/javascript">
$(function () {
$("#tabs").tabs({
});
});
</script>
What i want is to show a loading message inside the div of the active tab.
According to the widget doc, ajax should work outside the box if your href is an actual link :
To customize loading message, you can use the spinner option :
Fetch external content via Ajax for
the tabs by setting an href value in
the tab links. While the Ajax request
is waiting for a response, the tab
label changes to say "Loading...",
then returns to the normal label once
loaded.
<script>
$(function() {
$( "#tabs" ).tabs({
spinner: "<em>My Loading Msg</em>",
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
}
});
});
</script>
Why don't you just set the tab label to "loading" onclick and change it to whatever you want once you get a response back from your AJAX?
$(function () {
$("#tabs").tabs();
$("#tab1").click(function() {
$(this).val("Loading...");
$.ajax({
blablabla...
success: function() {
$("#tab1").val("Tab 1");
}
});
});
This should give you an idea, obviously the function could be written better to act on each tab.
I think what you are after already exists in the jquery ui for Tabs.
The HTML content of this string is
shown in a tab title while remote
content is loading.
http://jqueryui.com/demos/tabs/#option-spinner
Hope this helps!
From your example am I correct in assuming that you want to navigate to another page when the user clicks on either of the second two tabs, but you want a loading message to be displayed while you are waiting for the next tab to load?
If so, you could do it by keeping a loading message in the other tabs like so:
<input type="hidden" id="modelId" value="<%=Model.Id%>" />
<div id="tabs">
<ul>
<li>
User Profile
</li>
<li>
Edit
</li>
<li>
Delete AccountT
</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("UserProfile", Model); %>
</div>
<div id="tabs-2">
<p>Loading, please wait...</p>
</div>
<div id="tabs-3">
<p>Loading, please wait...</p>
</div>
</div>
And doing the redirection to your other pages in your javascript, doing it something like this:
$(document).ready(document_ready);
function document_ready()
{
$("tabs").bind("tabsselect", onTabSelected);
}
function onTabSelected(event, ui)
{
var modelId = $("#modelId").val();
switch (ui.panel.id)
{
case "tabs-2":
window.location.href = "/User/EditUser/" + modelId;
break;
case "tabs-3":
window.location.href = "/User/Delete/" + modelId;
break;
}
}

Resources