How to initialize pages in jquery mobile? pageinit not firing - jquery-mobile

What's the right way to initialize objects on a jquery mobile page? The events docs say to use "pageInit()" with no examples of that function, but give examples of binding to the "pageinit" method (note case difference). However, I don't see the event firing at all in this simple test page:
<html>
<body>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script>
<div data-role="page" id="myPage">
test
</div>
<script>
$("#myPage").live('pageinit',function() {
alert("This never happens");
});
</script>
</body>
</html>
What am I missing? I should add that if you change pageinit to another event like pagecreate this code works.
---- UPDATE ----
This bug is marked as "closed" in the JQM issue tracker. Apparently opinions differ about whether this is working properly or not.

It started working when I embedded script within page div:
<body>
<div id="indexPage" data-role="page">
<script type="text/javascript">
$("#indexPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
Used jQuery Mobile 1.0RC1

.live() is deprecated, suggestion is to use .on() in jQuery 1.7+ :
<script type="text/javascript">
$(document).on('pageinit', '#indexPage', function(){
// code
});
</script>
Check the online doc for more information about .on(): http://api.jquery.com/on/

Turns out this is a bug in 1.0b3 that is fixed in the current head. So if you want a fix now, you gotta grab the latest from git. Or wait for the next release.

jQuery(document).live('pageinit',function(event){
centerHeaderDiv();
updateOrientation();
settingsMenu.init();
menu();
hideMenuPopupOnBodyClick();
})
This is working now. Now all page transitions and all JQM AJAX functionality would work along with your defined javascript functions! Enjoy!

pageinit will not fire in case it is on secondary pages ( NOT MAIN page ) if it is written in common <script> tag...
I have such a problem - on secondary pages that are not loaded with 'rel="external"', the code in the common <script> tag is never executed...
really this code is always executed...
<body>
<div id="indexPage" data-role="page">
<script type="text/javascript">
$("#indexPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
althrough if you made "tabbed interface", using of "pageshow" is better

I had to put the script in the HTML page section which to me is a bug. It is loaded normally in a browser (not via AJAX) and all on a single page including javascript. We're not supposed to have to use document ready.

The easiest way I found to deal with this was to use JQM + Steal. It works like a charm as long as you put:
<script type='text/javascript' src='../steal/steal.js?mypage'></script>
Inside of the data-role='page' div.
Then use AJAX to connect anything that can use the same mypage.js and use an external link (by using the rel="external" tag) to anything that requires a different steal page.

#Wojciech Bańcer
From the jQuery docs:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

Try this:
$('div.page').live('pageinit', function(e) {
console.log("Event Fired");
});

$(document).on("pageinit", "#myPage", function(event) {
alert("This page was just enhanced by jQuery Mobile!");
});

The events don't fire on the initial page, only on pages you load via Ajax. In the above case you can just:
<script>
$(document).ready(function() {
alert("This happens");
});
</script>

Related

jQuery UI error: TypeError: this._addClass is not a function [duplicate]

I am having an issue getting a dialog to work as basic functionality. Here is my jQuery source imports:
<script type="text/javascript" src="scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.11.1.js"></script>
<script type="text/javascript" src="scripts/json.debug.js"></script>
Html:
<button id="opener">open the dialog</button>
<div id="dialog1" title="Dialog Title" hidden="hidden">I'm a dialog</div>
<script type="text/javascript">
$("#opener").click(function() {
$("#dialog1").dialog('open');
});
</script>
From the posts around seems like as a library import issue. I downloaded the JQuery UI Core, Widget, Mouse and Position dependencies.
Any Ideas?
Be sure to insert full version of jQuery UI. Also you should init the dialog first:
$(function () {
$( "#dialog1" ).dialog({
autoOpen: false
});
$("#opener").click(function() {
$("#dialog1").dialog('open');
});
});
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<button id="opener">open the dialog</button>
<div id="dialog1" title="Dialog Title" hidden="hidden">I'm a dialog</div>
if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true) from the second version will return the globally scoped jQuery variables to those of the first version.
Some times it could be issue with older version (or not stable version) of JQuery files
Solution use $.noConflict();
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
$("#opener").click(function() {
$("#dialog1").dialog('open');
});
});
// Code that uses other library's $ can follow here.
</script>
If you comment out the following code from the _Layout.cshtml page, the modal popup will start working:
</footer>
#*#Scripts.Render("~/bundles/jquery")*#
#RenderSection("scripts", required: false)
</body>
</html>
Change jQueryUI to version 1.11.4 and make sure jQuery is not added twice.
I just experienced this with the line:
$('<div id="editor" />').dialogelfinder({
I got the error "dialogelfinder is not a function" because another component was inserting a call to load an older version of JQuery (1.7.2) after the newer version was loaded.
As soon as I commented out the second load, the error went away.
Here are the complete list of scripts required to get rid of this problem.
(Make sure the file exists at the given file path)
<script src="#Url.Content("~/Scripts/jquery-1.8.2.js")" type="text/javascript">
</script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.24.js")" type="text/javascript">
</script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript">
</script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript">
</script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript">
</script>
and also include the below css link in _Layout.cshtml for a stylish popup.
<link rel="stylesheet" type="text/css" href="../../Content/themes/base/jquery-ui.css" />
I had a similar problem and in my case, the issue was different (I am using Django templates).
The order of JS was incorrect (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.
I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

Change page on swipeleft/swiperight

I have problem with mobile/tablet version of page which I create
I need this: When someone look at product detail and move him to right/left (touch/swipe) then I need load next/previous product detail (= Example: Now I on page with id=2 when I go right, then I load page with id=3, npw I on page with id=3 and I go left then I load page with id=2.. etc.. with different pages id).
I look in thread here, but this solution is not dynamic and I have problem applicate it. Next I inspirated in W3C here.
Now I have these codes which not work:
JS file:
$(document).on('pageinit', function() {
$('.epicFullscreen').bind('swipeleft', function(event,ui)
{
$.mobile.changePage("http://www.some_domain.cz/category/page_name-1/","slide");
});
$('.epicFullscreen').bind('swiperight', function()
{
$.mobile.changePage("http://www.some_domain.cz/category/page_name-3/","slide");
});
});
$(document).on('pagehide', function () { $(this).off('swipeleft swiperight'); });
HTML:
<script src="funkce/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="funkce/jquery.mobile-1.3.2.min.js" type="text/javascript"></script>
<script src="funkce/skripty.js" type="text/javascript"></script>
I need use old JQuery 1.7.1. because this site using it and everything works fine, with newer JQuery I can have new problems. For that I use older JQuery-mobile 1.3.2. which must work with JQuery 1.7.1. ("jQuery Mobile 1.3 supports jQuery 1.7 and newer") . I can´t include "jquery.mobile-1.3.2.min.css" because this styles not work together with my styles correctly.
HTML in body is like that:
<div class="epicFullscreen">
<img class="epicImg" src="../../data_9/11normal.jpg" alt="inspirace č.2" title="inspirace č.2" border="0" />
</div>
Now I have dynamic solution with arrows (right/left) and with adding correct urls with PHP, but on tablet/mobile user like using touch not clicking on arrows etc...
=> Where I have problem and why not work my current solution? And how I can change this static JS to dynamic JS?
try this simple code .....
$(document).on("swipeleft", '#'+event.target.id, function () {
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
alert(nextpage.attr('id'));
$.mobile.changePage(nextpage, "slide", false, true);
}
});
$(document).on("swiperight", '#'+event.target.id, function () {
var prevpage = $(this).prev('div[data-role="page"]');
if (prevpage.length > 0) {
$.mobile.changePage(prevpage, { transition: "slide", reverse: true }, true, true);
}
});
I found solution for that I make this answer. I simplify my problem and create simple page.
Code
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css">-->
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery.mobile-1.3.2.min.js" type="text/javascript"></script>
<script>
$(document).on("pageinit",function(){
var pathname = $(location).attr('href');
var leva = $('#le').attr("href");
var prava = $('#pr').attr("href");
$("body").on("swiperight",function(){
<!--alert("You swiped right!");-->
location.href=prava;
});
$("body").on("swipeleft",function(){
<!--alert("You swiped left!");-->
location.href=leva;
});
});
</script>
</head>
<body>
<div id="test_div" style="display: block;">
<img src="test.gif" width="100px">
<a id="le" href="http://www.some_domain.cz/category/page_name-1/">left</a>
<a id="pr" href="http://www.some_domain.cz/category/page_name-3/">right</a>
</div>
</body>
</html>
I have this one hack - in PHP I know on which page I am, which page is before and which is next, I add this links it to arrows (which have tag "a"). This function working perfect. But I use this functional code to get correct URL => I don´t need some big function in JQuery which can split actual url with RegEx, know on which page I am, know if exist next page etc... Now I must only style this code to my page, but this is working.
I thank Omar for his time and I close this topic.

jQuery click event not firing in jQueryMobile

Using jQuery jquery-1.9.1.js and jQueryMobile 1.3.1 (Chrome 26/Windows 7) I cannot see why one of these 'click' events bound to #one1 fires and the other doesn't:
HTML:
<div data-role="page" id="one" data-theme="a">
<div data-role="header" data-position="inline">
<h1>One</h1>
</div>
<div data-role="content" data-theme="a">
[one]
two
three
</div>
</div>
JavaScript:
<script>
$(document).on( "mobileinit", function() {
$(document).on('click', '#one1', function(e){
console.log('firing');
});
$('#one1').on("click", function() {
console.log('not firing');
});
});
</script>
When I run it in JSFiddle both events fire when not wrapped in the "mobileinit" event:
http://jsfiddle.net/9NRwa/
What am I missing here?
Intro
First thing first, mobileinit event should not be used for event binding. While it CAN be used like that mobileinit was not created for that purpose. It was created for jQuery Mobile parameter auto-initialization, so it should not be used for event binding.
Correct way is to use proper page events like pageinit. For more information about page events take a look at my other answer that covers various jQuery Mobile page events and their difference towards usual jQuery document ready paradigm: jQuery Mobile: document ready vs page events.
Not let me answer this question. Events like click can be bound in a few different ways.
Lets look at examples you have used:
Various ways of event binding with jQuery
First example
$(document).on('click', '#one1', function(e){
console.log('firing');
});
This first example is something new that came to use first with now deprecated method live.
Basically it's an event delegation mechanism that allows you to bind event handlers not just to all existing instances of a given node type, but also to any future instances of a given node type (by "type" I mean a set of DOM nodes matched by a given jQuery selector). What I want to say here is, during the event binding that element don't need to exist in a DOM, basically this method works by binding event handlers to the document itself and then reacting to all the events that bubble up through the DOM. So it doesn't matter if element #one1 exist or not during the event binding. You can create it dynamically later and it will still work.
Second example
$('#one1').on("click", function() {
console.log('not firing');
});
This is on old way of event binding. It requires that event exists in the DOM before event can be bind. In your case you were trying to bind this click event to the element that didn't exist in a DOM at that point in time. It doesn't matter it was loaded after the binding process.
Working example
jsFiddle example: http://jsfiddle.net/Gajotres/QmNsa/
Take a look at this example. There you will see 5 different ways of click event binding in jQuery Mobile:
2 click event are bound in HEAD, before page is initialized into the DOM
2 click events are bound in HEAD in pagebeforeshow event, basically this is also a delegation of binding because event are bound when page is about to be shown and already inside a DOM
1 click event is bound in a BODY after all page content. Because all content is loaded inside a DOM at this point this click event will work.
HTML :
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
<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/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<script>
$(document).on('click', '#one1', function(e){
// This example will work because it was bind with event delegation process
console.log('Firing 1');
});
$('#one1').on("click", function() {
// This example will not work because event do not exist in this moment
console.log('Not firing');
});
$(document).on( "pagebeforeshow", function() {
// This example will work because it was bind with event delegation process
$(document).on('click', '#one1', function(e){
console.log('Firing 2');
});
// This example will work because element exist in a DOM during the pagebeforeshow event
$('#one1').on("click", function() {
console.log('Firing 3');
});
});
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="b" data-role="header">
<h1>Index page</h1>
</div>
<div data-role="content">
[one]
</div>
</div>
<script>
$('#one1').on("click", function() {
// This example will work because we are binding it when element is already loaded into the DOM
console.log('Firing 4');
});
</script>
</body>
</html>
Conclusion
Do not use mobileinit event for event binding, it will trigger before page is loaded into the DOM and only events bind with delegation will work.
Bind your events in a correct jQuery Mobile page events.
Usefull links regarding this topic:
jQuery Live() Method And Event Bubbling
While live method is deprecated on method should be used instead. In some benchmarks on method is 2x faster.
jQuery Mobile: document ready vs page events
Various jQuery Mobile page events
What does “event bubbling” mean?
As the docs stated:
Because the mobileinit event is triggered immediately, you'll need to
bind your event handler before jQuery Mobile is loaded
Currently, your mobileinit event are running after jQuery Mobile is loaded since jsFiddle will execute your javascript code after finish loaded any libraries you've chosen from the sidebar. To make it works, your structure should look like this:
<script src="jQuery library include first"></script>
<script>
$(document).on("mobileinit", function() {
// Your code here
});
</script>
<script src="jQuery Mobile include last"></script>

Overriding data-ajax="false" from parent container in jquerymobile

I am using the method noted here in the docs to set data-ajax="false" on a parent container for my site but I do have a few cases where I want the page to load via Ajax.
Is there a way to set the default on the parent container but allow individual links to override that setting? Adding data-ajax="true" to the individual links doesn't seem to work.
To set default for full page load:
$(document).on("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
To set individual, use data-ajax=true.
Somehow other suggestions didn't work for me. But this one did work. Tested.
This script disables all ajax links in the page jquery mobile - and those that should be ajax ones can be used as the a-link below with data-ajax=true.
<head>
<!-- ..... -->
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(document).on("mobileinit", function () {
// Reference: http://jquerymobile.com/demos/1.1.0/docs/api/globalconfig.html
$.extend($.mobile, {
linkBindingEnabled: false,
ajaxEnabled: false
});
});
</script>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js"></script>
<!-- ..... -->
</head>
<body>
<a href="holysmokewheredidtheajaxgo.html" data-ajax=true>Well, I'm still ajax. That's true!</a>
</body>

jquery mobile + phonegap onclick

I've been trying to figure this out but still stuck.
so I'm using PhoneGap for iOS and JQueryMobile.
I'm trying to show alert when a button is clicked.
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<!-- If your application is targeting iOS BEFORE 4.0 you MUST put json2.js from http://www.JSON.org/json2.js into your www directory and include it here -->
<script type="text/javascript" charset="utf-8" src="cordova-1.6.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js">
</script>
and I have
this
Login
$(document).ready("#button").click(function() {
alert('button clicked');
});
when I tried to launch this in chrome, this works fine.
however, when I used iphone simulator, it doesnt show anything.
For a normal web application you would use dom ready i.e.
$(function(){ // <-- this is a shortcut for $(document).ready(function(){ ... });
$('#button').click(function(){
alert('button clicked');
});
});
However in a JQM application it is much more useful to bind to 'pageinit' i.e.
$(document).on('pageinit','[data-role=page]',function(){
$('#button').click(function(){
alert('button clicked');
});
});
Binding to pageinit works better because JQM inserts new pages into the same dom as the first page. Because of this all of your code in dom ready doesn't get called again. So that first bit of code i put above will only work for that first page in your JQM application. The second will work no matter what page your button is in. Let me know if I can clarify this further for you.

Resources