Apply jquery mobile only a portion of page? - javascript

I have a sample page which we have design very well. Now, we need to use jquery mobile only a portion of our page. The problem is that, when I add jquery mobile it is messing all my UI stuff. Is there is a way to apply jquery mobile only a portion of page?

There are several ways of achieving this, and you can find them in my other ARTICLE, or find it HERE. Search for chapter called: Methods of markup enhancement prevention.
And here's a short description with examples. There are several solutions and you will need to pick right one:
Methods of markup enhancement prevention:
This can be done in few ways, sometimes you will need to combine them to achieve a desired result.
Method 1:
It can do it by adding this attribute:
data-enhance="false"
to the header, content, footer container.
This also needs to be turned in the app loading phase:
$(document).one("mobileinit", function () {
$.mobile.ignoreContentEnabled=true;
});
Initialize it before jquery-mobile.js is initialized (look at the example below).
More about this can be found here:
http://jquerymobile.com/test/docs/pages/page-scripting.html
Example: http://jsfiddle.net/Gajotres/UZwpj/
To recreate a page again use this:
$('#index').live('pagebeforeshow', function (event) {
$.mobile.ignoreContentEnabled = false;
$(this).attr('data-enhance','true');
$(this).trigger("pagecreate")
});
Method 2:
Second option is to do it manually with this line:
data-role="none"
Example: http://jsfiddle.net/Gajotres/LqDke/
Method 3:
Certain HTML elements can be prevented from markup enhancement:
$(document).bind('mobileinit',function(){
$.mobile.page.prototype.options.keepNative = "select, input";
});
Example: http://jsfiddle.net/Gajotres/jjETe/

Related

jQuery Mobile: Markup Enhancement of dynamically added content

I was wondering how can I enhance dynamically jQuery Mobile page?
I have tried to use these methods:
$('[data-role="page"]').trigger('create');
and
$('[data-role="page"]').page();
Also how can I prevent enhancement markup of check boxes only?
Intro:
There are several ways of enhancing dynamically created content markup. It is just not enough to dynamically add new content to jQuery Mobile page, new content must be enhanced with classic jQuery Mobile styling. Because this is rather processing heavy task there need to be some priorities, if possible jQuery Mobile needs to do as less enhancing as possible. Don't enhance whole page if only one component need's to be styled.
What does this all means? When page plugin dispatches a pageInit event, which most widgets use to auto-initialize themselves. it will automatically enhance any instances of the widgets it finds on the page.
However, if you generate new markup client-side or load in content via Ajax and inject it into a page, you can trigger the create event to handle the auto-initialization for all the plugins contained within the new markup. This can be triggered on any element (even the page div itself), saving you the task of manually initializing each plugin (listview button, select, etc.).
With this in mind lets discuss enhancement levels. There are three of them and they are sorted from the less resource demanding to higher ones:
Enhance a single component/widget
Enhance a page content
Enhance a full page content (header, content, footer)
Enhance a single component/widget:
Important: The below enhancement methods are to be used only on current/active page. For dynamically inserted pages, those pages and their contents will be enhanced once inserted into DOM. Calling any method on dynamically created pages / other than the active page, will result an error.
Every jQuery Mobile widget can be enhanced dynamically:
Listview :
Markup enhancement:
$('#mylist').listview('refresh');
Removing listview elements:
$('#mylist li').eq(0).addClass('ui-screen-hidden');
Enhancement example: http://jsfiddle.net/Gajotres/LrAyE/
Note that the refresh() method only affects new nodes appended to a list. This is done for performance reasons.
One of a listview high-points is a filtering functionality. Unfortunately, for some reason, jQuery Mobile will fail to dynamically add filter option to an existing listview. Fortunately there's a workaround. If possible, remove current listview and add another one with a filer option turned on.
Here's a working example: https://stackoverflow.com/a/15163984/1848600
$(document).on('pagebeforeshow', '#index', function(){
$('<ul>').attr({'id':'test-listview','data-role':'listview', 'data-filter':'true','data-filter-placeholder':'Search...'}).appendTo('#index [data-role="content"]');
$('<li>').append('Audi').appendTo('#test-listview');
$('<li>').append('Mercedes').appendTo('#test-listview');
$('<li>').append('Opel').appendTo('#test-listview');
$('#test-listview').listview().listview('refresh');
});
Button
Markup enhancement:
$('[type="button"]').button();
Enhancement example: http://jsfiddle.net/Gajotres/m4rjZ/
One more thing, you don't need to use a input element to create a button, it can be even done with a basic div, here's an example: http://jsfiddle.net/Gajotres/L9xcN/
Navbar
Markup enhancement:
$('[data-role="navbar"]').navbar();
Enhancement example: http://jsfiddle.net/Gajotres/w4m2B/
Here's a demo how to add dynamic navbar tab: http://jsfiddle.net/Gajotres/V6nHp/
And one more in pagebeforecreate event: http://jsfiddle.net/Gajotres/SJG8W/
Text inputs, Search inputs & Textareas
Markup enhancement:
$('[type="text"]').textinput();
Enhancement example: http://jsfiddle.net/Gajotres/9UQ9k/
Sliders & Flip toggle switch
Markup enhancement:
$('[type="range"]').slider();
Enhancement example: http://jsfiddle.net/Gajotres/caCsf/
Enhancement example during the pagebeforecreate event: http://jsfiddle.net/Gajotres/NwMLP/
Sliders are little bit buggy to dynamically create, read more about it here: https://stackoverflow.com/a/15708562/1848600
Checkbox & Radiobox
Markup enhancement:
$('[type="radio"]').checkboxradio();
or if you want to select/deselect another Radiobox/Checkbox element:
$("input[type='radio']").eq(0).attr("checked",false).checkboxradio("refresh");
or
$("input[type='radio']").eq(0).attr("checked",true).checkboxradio("refresh");
Enhancement example: http://jsfiddle.net/Gajotres/VAG6F/
Select menu
Markup enhancement:
$('select').selectmenu();
Enhancement example: http://jsfiddle.net/Gajotres/dEXac/
Collapsible
Unfortunately collapsible element can't be enhanced through some specific method, so trigger('create') must be used instead.
Enhancement example: http://jsfiddle.net/Gajotres/ck6uK/
Table
Markup enhancement:
$(".selector").table("refresh");
While this is a standard way of table enhancement, at this point I can't make it work. So instead use trigger('create').
Enhancement example: http://jsfiddle.net/Gajotres/Zqy4n/
Panels - New
Panel Markup enhancement:
$('.selector').trigger('pagecreate');
Markup enhancement of content dynamically added to Panel:
$('.selector').trigger('pagecreate');
Example: http://jsfiddle.net/Palestinian/PRC8W/
Enhance a page content:
In case we are generating/rebuilding whole page content it is best to do it all at once and it can be done with this:
$('#index').trigger('create');
Enhancement example: http://jsfiddle.net/Gajotres/426NU/
Enhance a full page content (header, content, footer):
Unfortunately for us trigger('create') can not enhance header and footer markup. In that case we need big guns:
$('#index').trigger('pagecreate');
Enhancement example: http://jsfiddle.net/Gajotres/DGZcr/
This is almost a mystic method because I can't find it in official jQuery Mobile documentation. Still it is easily found in jQuery Mobile bug tracker with a warning not to use it unless it is really really necessary.
Note, .trigger('pagecreate'); can suppose be used only once per page refresh, I found it to be untrue:
http://jsfiddle.net/Gajotres/5rzxJ/
3rd party enhancement plugins
There are several 3rd party enhancement plugins. Some are made as an update to an existing method and some are made to fix broken jQM functionalities.
Button text change
Unfortunately cant found the developer of this plugin. Original SO source: Change button text jquery mobile
(function($) {
/*
* Changes the displayed text for a jquery mobile button.
* Encapsulates the idiosyncracies of how jquery re-arranges the DOM
* to display a button for either an <a> link or <input type="button">
*/
$.fn.changeButtonText = function(newText) {
return this.each(function() {
$this = $(this);
if( $this.is('a') ) {
$('span.ui-btn-text',$this).text(newText);
return;
}
if( $this.is('input') ) {
$this.val(newText);
// go up the tree
var ctx = $this.closest('.ui-btn');
$('span.ui-btn-text',ctx).text(newText);
return;
}
});
};
})(jQuery);
Working example: http://jsfiddle.net/Gajotres/mwB22/
Get correct maximum content height
In case page header and footer has a constant height content div can be easily set to cover full available space with a little css trick:
#content {
padding: 0;
position : absolute !important;
top : 40px !important;
right : 0;
bottom : 40px !important;
left : 0 !important;
}
And here's a working example with Google maps api3 demo: http://jsfiddle.net/Gajotres/7kGdE/
This method can be used to get correct maximum content height, and it must be used with a pageshow event.
function getRealContentHeight() {
var header = $.mobile.activePage.find("div[data-role='header']:visible");
var footer = $.mobile.activePage.find("div[data-role='footer']:visible");
var content = $.mobile.activePage.find("div[data-role='content']:visible:visible");
var viewport_height = $(window).height();
var content_height = viewport_height - header.outerHeight() - footer.outerHeight();
if((content.outerHeight() - header.outerHeight() - footer.outerHeight()) <= viewport_height) {
content_height -= (content.outerHeight() - content.height());
}
return content_height;
}
And here's a live jsFiddle example: http://jsfiddle.net/Gajotres/nVs9J/
There's one thing to remember. This function will correctly get you maximum available content height and at the same time it can be used to stretch that same content. Unfortunately it cant be used to stretch img to full content height, img tag has an overhead of 3px.
Methods of markup enhancement prevention:
This can be done in few ways, sometimes you will need to combine them to achieve a desired result.
Method 1:
It can do it by adding this attribute:
data-enhance="false"
to the header, content, footer container.
This also needs to be turned in the app loading phase:
$(document).one("mobileinit", function () {
$.mobile.ignoreContentEnabled=true;
});
Initialize it before jquery-mobile.js is initialized (look at the example below).
More about this can be found here:
http://jquerymobile.com/test/docs/pages/page-scripting.html
Example: http://jsfiddle.net/Gajotres/UZwpj/
To recreate a page again use this:
$('#index').live('pagebeforeshow', function (event) {
$.mobile.ignoreContentEnabled = false;
$(this).attr('data-enhance','true');
$(this).trigger("pagecreate")
});
Method 2:
Second option is to do it manually with this line:
data-role="none"
Example: http://jsfiddle.net/Gajotres/LqDke/
Method 3:
Certain HTML elements can be prevented from markup enhancement:
$(document).bind('mobileinit',function(){
$.mobile.page.prototype.options.keepNative = "select, input";
});
Example: http://jsfiddle.net/Gajotres/gAGtS/
Again initialize it before jquery-mobile.js is initialized (look at the example below).
Markup enhancement problems:
Sometimes when creating a component from scratch (like listview) this error will occur:
cannot call methods on listview prior to initialization
It can be prevented with component initialization prior to markup enhancement, this is how you can fix this:
$('#mylist').listview().listview('refresh');
Markup overrding problems:
If for some reason default jQuery Mobile CSS needs to be changed it must be done with !important override. Without it default css styles can not be changed.
Example:
#navbar li {
background: red !important;
}
jsFiddle example: http://jsfiddle.net/Gajotres/vTBGa/
Changes:
01.02.2013 - Added a dynamic navbar demo
01.03.2013 - Added comment about how to dynamically add filtering to a listview
07.03.2013 - Added new chapter: Get correct maximum content height
17.03.2013 - Added few words to the chapter: Get correct maximum content height
29.03.2013 - Added new content about dynamically created sliders and fix an example bug
03.04.2013 - Added new content about dynamically created collapsible elements
04.04.2013 - Added 3rd party plugins chapter
20.05.2013 - Added Dynamically added Panels and contents
21.05.2013 - Added another way of setting full content height
20.06.2013 - Added new chapter: Markup overrding problems
29.06.2013 - Added an important note of WHEN to use enhancement methods
From JQMobile 1.4 you can do .enhanceWithin() on all the children http://api.jquerymobile.com/enhanceWithin/
var content = '<p>Hi</p>';
$('#somediv').html(content);
$('#somediv').enhanceWithin();

jQuery Mobile "enhance" dynamically re-generated html

jQuery Mobile 1.2.0
I generate the HTML using JavaScript ($(selector).html(content)), add it to the DOM and then display it ($.mobile.changePage()).
Then I invoke an AJAX call, get some data, and re-generate the html (but the parent element, the same $(selector), stays the same, I just change its html(...)).
At this poing the HTML is not "enhanced" by jQM, no styling applied on it.
Now according to the docs I should simply call the page() function on the parent element, i.e $(selector).page().
Other places in the docs suggest triggering the create event, i.e $(selector).trigger("create").
The problem is that non of the above two methods works - the styling of jQM is not applied.
Looking at the code of jQM, I've tried triggering the pagecreate event on that element and it does work, but, this is not documented anywhere, so I'm uncertain of it, especially concerning future releases of jQM.
At some poing in the docs I've read that I can call page() on a page only once..
Anyway, is there any concise/standard way to tell jQM to "enhance" the whole element and its child-elements? Or should I simply stay with triggering the pagecreate event?
Thank you!
To recreate a whole page use this:
$(selector).trigger("pagecreate");
This was my answer to a simmilar question: https://stackoverflow.com/a/14011070/1848600. There's an example of page recreation. Take a look, this should probably solve your problem.
What is the scope of
$(selector).trigger("create");
You should be able to add any elements on the 'pagecreate' event which comes right before 'pageshow' jqm styling is applied to elements. For example I dynamically add a header/footer like this
$(document).on('pagecreate', "[data-role=page]", function() {
var header = "<div data-role='header'>some header stuff</div>";
var footer= "<div data-role='footer'>some footer stuff</div>";
$(this).prepend(header);
$(this).append(footer);
$("[data-role=header]").fixedtoolbar({tapToggle: false});
$("[data-role=footer]").fixedtoolbar({tapToggle: false});
});
Make sure you're using jquery 1.7 or above I think that's when the on method was introduced;
It sounds like you may be generating the DOM and then changing the page, try it the other way around go to the page first then dynamically edit the dom.
EDIT
set the reload page option to true
$.mobile.changePage($(page), {reloadPage: true});
Edit 2
$(selector).children().each(function(){
$(this).trigger('create');
})

jQuery call function when language in selectbox is changed

I have the following problem.
To translate a website, I'm using the jQuery Localize plugin.
This works fine. However, I want a CSS styled selectbox with flags and languages, and when a different option is selected the call to $("[data-localize]").localize("example", { language: $(this).attr('value') should be made to translate the page.
This code I'm currenly using, and it works fine for a plain, not-styled selectbox.
<script type="text/javascript">
$(function() {
$('#polyglot-language-options').change(function() {
if ($(this).attr('value') == "en") {
$("[data-localize]").localize("example", {
language: $(this).attr('value')
});
}
else if ($(this).attr('value') == "nl") {
location.reload();
}
});
});
</script>
But I want to style it, so I tried to integrate the "polyglot" language switcher. However, the current code doesn't work.
How can I integrate the $("[data.localize]").localize(); function in this code:
$('#polyglotLanguageSwitcher').polyglotLanguageSwitcher({
effect: 'fade'
});
This plugin (source code) does not follow the guidelines for jQuery plugin design. The bugs I found quickly:
It does not allow chaining, because it does not return this
It works only on one element at a time (does not use each())
It has a queer element hierarchy. It seems to require an element with an id, containing a form containing a select (as in the demo). In my opinion, such a plugin should be called on the language select element only.
It seems to navigate automatically, wanting to be configured with the page structure. Each of the li items in that fancy box contains a link to the respective page.
Therefore, it does neither trigger the form it live in or fire the change event you want to listen to.
As it stands, you can't use this particular plugin as you want to. If you want to fix all the bugs, I wish you a happy time :-) Nonetheless it might be possible to manipulate the plugin code, to let you register callbacks on select events (where you can invoke the localisation plugin). Otherwise, you will need to choose an other select plugin (or build one yourself from scratch, adapting the existing code)

Is it possible to create element on the fly with jQuery Mobile?

I have an app built using jQuery (and using various jQuery-UI tools).
For some reason, i have to port it to smartphones/tablet computer, and decided to use jQuery Mobile for that (in order to minimize the number of changes).
In my vanilla app, I created some elements of the page on the fly, depending of user interactions.
For example a slider could be created like that (p is an object with a bunch of params):
function createSlider(p){
return $("<div/>",{
"id":p.id,
"class":p.divClass,
}).slider({
"orientation": p.align,
"min":p.constraint.min,
"max":p.constraint.max,
"step":p.step,
"value":p.curVal,
"animate":"normal"
/*and some event handling here, but it doesn't matter*/
});
}
And it will produce a nice looking slider. Now it looks like:
function createSlider(p){
return $("<range/>",{
"id":p.id,
"class":p.divClass,
"min":p.constraint.min,
"max":p.constraint.max,
"step":p.step,
"value":p.curVal,
});
}
But as it's created on the fly, all the stuff done by jQuery Mobile on the page load isn't done on it.
Is there a way to force that initialization without writing the slider in the html?
Thanks.
EDIT: I found in the doc that it could be achieved using container.trigger("create");
However this does not work yet.
EDIT2: Ok create was the solution.
According to the documentation (see edit in the question), using trigger("create") on the containing element works.
And to make that work, you also need to remember that range is an input type and not a tag...
Working solution:
function createSlider(){
return $("<input/>",{
"type":"range",
"id":"sl",
"min":0,
"max":15,
"step":1,
"value":1,
});
}
function appendSlider(){
$("#yourdiv").append(createSlider()).trigger("create");
}
As a sidenote, the documentation for jQuery mobile lacks a search option.
Try calling .page() on the container the content is being added to. Alternatively, adding .page() to the content you're returning may also work.

Making a span/div/p href-like or stopping href "executing" links

I have the problem to "stop" href executing any links.
So my question is:
1) Is it possible replace href-elements that generate internal (#) links with any component, maybe <p>, <div> or <span> (or whatever could be working) that keep the same behaviour of <a> element (hovering, underlined etc) but not executing any link?
2) Alternative, a "trick" to avoiding href elements execute links?
1 or 2 without using jquery or any other js library possibly
Thanks Randomize
There are all sorts of tricks that can be employed to do this kind of thing, but what you need to be careful of is modifying the behaviour from that which the users have come to expect from a browser.
For example , it would be possible to swap the meaning of 'OK' & 'Cancel' buttons, but this would just confuse the user. (An extreme example, I know, but you get the idea)
If you could supply some more information about why you are trying to do this, there may be a better way of approaching things.
You can either add an onclick attribute to specific <a> elements:
Or modify the href like this:
To make them look like links, without redirecting the browser.
If instead, you already have a bunch of links with hrefs, and you simply wish to make them all non-redirecting, then the following jQuery will do this to all links on the page:
$(function () {
$('a').click(false);
});
Although nice and short, the above only works with jQuery-1.4.3+. If you are using an older version, then you can use the expanded form:
$(function () {
$('a').click(function () { return false; });
});
Yes. You can prevent links from the default action - the recommended way is to have links work normally (in case JS is disabled or not available - think "mobile browsers"), and then override the default action with JS.
Unfortunately, due to cross-browser incompatibilities, there are three ways to do this ("traditional","W3C" and "IE") and you need all of them: stopPropagation(), cancelBubble and return false. See a complete example at QuirksMode: http://www.quirksmode.org/js/events_order.html#link9
(Incidentally most JS frameworks abstract this away, so in jQuery you'd do this:
$('a').click(function(event){
// do something on click here
event.preventDefault();
});
This does the same thing as the QuirksMode example, but is a easier-to-read example.)
TO disable the link via js add onclick="this.href='javascript:void(0)';" like so:
link text
You can use a similar tactic to make other elements work link links:
<div onclick="this.href='http://www.mysite.com';"></div>
This is working in IE, chrome and firefox:
text link
In the function return void(0):
function functionX() {
...
return void(0);
}

Categories

Resources