Seems to me like this should work (based on answers to other questions here on SM), but I'm not getting any results...
Here's my code in the head of the page:
Second edit:
<script type="text/javascript">
function capitalizeFirstLetter(string){
return string.charAt(0).toUpperCase() + string.slice(1);
}
$(document).delegate('#sun, #mon, #tue, #wed, #thu, #fri, #sat', 'pageshow' , function() {
var days = ['sun','mon','tue','wed','thu','fri','sat'],
output = [],//create an output buffering variable
d = new Date();
for(var x=0; x<days.length; x++){
//rather than manipulate the DOM every iteration of the loop we add a string of HTML to an array
output.push('<li>' + capitalizeFirstLetter(days[x]) + '</li>');
}
//now we add the buffered data to the listview and either refresh or initialize the widget
var $cNav = $('#custom-navbar')
$cNav.append(output.join(''));
//if the listview has the `ui-listview` class then it's been initialized, and the widget needs to be refreshed, otherwise it needs to be initialized
if ($cNav.hasClass('ui-navbar')) {
$cNav.navbar('refresh');
} else {
$cNav.navbar();
}
});
</script>
And here's my code in the body:
<div data-role="content">
<div data-role="navbar" style="margin: -10px 0 15px 0;">
<ul id="custom-navbar"></ul>
</div>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
$(document).delegate('#sun', 'pageshow' , function() {
alert("!");
var days = ['sun','mon','tue','wed','thu','fri','fri','sat'],
output = [];//create an output buffering variable
for(var x=0; x<days.length; x++){
alert(days[x]);
//rather than manipulate the DOM every iteration of the loop we add a string of HTML to an array
output.push('<li><a data-ajax="false" href="#' + days[x] + '">' + days[x] + '</a></li>');
}
//now we add the buffered data to the listview and either refresh or initialize the widget
var $cNav = $('#custom-navbar')
$cNav.append(output.join(''));
//if the listview has the `ui-listview` class then it's been initialized, and the widget needs to be refreshed, otherwise it needs to be initialized
if ($cNav.hasClass('ui-listview')) {
$cNav.listview('refresh');
} else {
$cNav.listview();
}
});
</script>
<script src="../js/jquery.mobile-1.0.1.js"></script>
Since this code runs each pageshow event, you will be getting multiple listings when users navigate to, away, and then back to the page. You could use the pageinit event instead: http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/events.html
Update
The error in your page comes from here:
$('ul#custom-navbar').append('<li/>', {
.append('<a/>', {
'href' = "#" + days[x],
'data-ajax' = "false",
'text' = days[x]
});
});
Do you see it? You've got an extra , { and are missing a bit of syntax to make this make sense. You're also using equal signs where you should be using colons (since you're setting properties of an object):
$('ul#custom-navbar').append(
$('<li/>').append('<a/>', {
'href' : "#" + days[x],
'data-ajax' : "false",
'text' : days[x]
})
);
This creates a list-item, then appends a link to it with some attributes set.
Note that you can copy my code, paste it over your code (in your document) and it will work fine. I've tested it using my console.
In a general sense, you should learn to use your console, it will help you an amazing amount. For instance I found the error on your page in about 30 seconds...
Well, from the jQuery Mobile website they directly recommend not binding to $(document).ready() due to their use of some ajax magic behind the scenes and instead recommend performing something similar to what you're doing but with pageinit instead of pageshow. From what I can see in the documentation they should be (for this) functionally equivalent. Have you tried binding pageshow or pageinit after loading jqm?
http://jquerymobile.com/demos/1.1.0-rc.1/docs/api/events.html
Important: Use pageInit(), not $(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.
I guess 'pageshow' event is of jquery mobile framework. If am right, then you should add jquery mobile script tag before your script.
Well firstly use
$('ul#custom-navbar').listview();
not $('ul#custom-navbar').listview('refresh'); this won't work if the element isn't initialized
But If you added the html attr data-role="listview" on the ul, the on pageshow jQM will automatically init the listview, if so and then you added elements to it, then you would need to run $('ul#custom-navbar').listview('refresh'); I recommend you do this instead.
Also you need to put the $('ul#custom-navbar').listview(); within your live function like someone else mentioned, jQM isn't loaded when you call it, and you should be using the pageinit event, pageshow also fires when you navigate back to the page (thru the back button etc), you don't want to init it twice. Read up on those two, optimally you'd be using both to cleanly handle JS.
PS: I'm glad you are properly listening to the pageinit/pageshow events and not using document.ready, also I suggest starting those listeners in the mobileinit handler, e.g.
$(document).bind("mobileinit", function(){//your pageinit/pageshow listeners here and also the .live function is deprecated now, use $(document).on('pageinit pageshow', 'div:jqmData(role="page"), div:jqmData(role="dialog")', function(oEvent){
Related
I'm trying to use the pushPage() function of the OnsenUI 2 (rc15 as of now). Alongside the OnsenUI, I'm using jQuery 3.
Here is my function that upon clicking certain elements should push a page:
$(".tile_handler").on("click", ".imalink", function () {
var link = $(this).data().href;
if(link != null){
document.querySelector("#myNavigator").pushPage(link, { animation: "slide-ios" });
}
})
When I push the page for the first time, it works fine. I use the iOS back button to return. Then I click it again and I get this error (and increasingly more as I repeat the process):
[index.js:450] Uncaught (in promise) pushPage is already running.
Here is another function that is supposed to load splitter pages:
$(".splitter_item").click(function () {
var address = $(this).data('address');
$('#content')[0].load(address).then(menu.close.bind($('#menu')[0]));
})
When I switch between two pages via Splitter it starts throwing this ( and more every time I switch between pages)
[undefined:1] Uncaught (in promise) Splitter side is locked.
What I assume is happening is that I load a page, leave it and when I access it again, it loads the page again. However that doesn't seem to be the behavior shown in OnsenUI examples such as this:
document.addEventListener('init', function(event) {
var page = event.target;
if (page.id === 'page1') {
page.querySelector('#push-button').onclick = function() {
document.querySelector('#myNavigator').pushPage('page2.html', {data: {title: 'Page 2'}});
};
} else if (page.id === 'page2') {
page.querySelector('ons-toolbar .center').innerHTML = page.data.title;
}
});
There is the popPage() function which should delete previously loaded page and would prevent this. But the references don't use it, so I assume I'm doing something wrong. But I don't know what.
UPDATE:
I managed to reproduce both problems in CodePen. Here is the Splitter error and here is the pushPage() one. It seems like the pushPage() one is a problem with my function as it adds a pushPage() request every time I click it, not sure why though.
Both errors only seem to happen in Ripple emulator (via VS2015). I don't seem to be able to reproduce them in Android Emulator (but the $(".tile_handler").on("click", ".imalink", function () { code fires incorreclty multiple times anyway). I'm testing this further.
Basically each time you push a page, that page fires an init event. However Onsen still keeps the initial page in the dom.
Navigator example (the same logic applies to the splitter one):
<ons-navigator>
<ons-page id="dashboard">
<div class="imalink" data-href="request_list.html"></div>
</ons-page>
</ons-navigator>
You have an init event for dashboard. Then you click the tile and go to another page.
Then request_list fires its own init event. However our initial page is still in the dom.
<ons-navigator>
<ons-page id="dashboard" style="display: none">
<div class="imalink" data-href="request_list.html"></div>
</ons-page>
<ons-page id="request_list">
...
</ons-page>
</ons-navigator>
You have something like this. However the following is called a second time:
$(".tile_handler").on("click", ".imalink", function () {
...
})
Which adds the listeners once more. $el.on("click") like an alias of addEventListener, meaning you are adding more and more listeners.
So whenever you navigate you keep adding them because the initial page was never removed from the dom.
Alternative solutions:
Use only the current page (e.target)
$('selector') // instead of this
$(e.target).find('selector') // use this
That way you limit to only finding elements within the page which you just created.
Enable the handlers from the start.
Since you are using jQuery there is actually a simpler way to do the things without relying on the init event.
Just do this outside of any init handler:
$(document).on("click", ".tile_handler .imalink", function () { ... })
This actually means that the handler is attached to the document itself and the handler will be called only when the target is .tile_handler .imalink - so it works with any future imalinks which you create.
This may not be the most efficient approach, but is definitely one of the simplest.
Both errors which you mention are actually a safe measure from you pushing or doing some action twice by mistake if you double click a button/link for example.
They appear when you try to make an action while an animation is running. As you can see in the examples generally there is no problem to push a page twice or more, as long as you start the second push after the first one is finished.
Here are demos with your exact code for both the splitter and navigator.
So the error does not come from the code which you provided, its someplace elsewhere.
The only thing I can come up with is that the behaviour which you mentioned would be seen if for some reason the popPage method failed to finish correctly. Maybe if you provide us with your own codepen where the issue can be reproduced we could debug it further.
An alternative, though highly NOT recommended would be to force the state before you do your action. This however would not be solving the problem, rather only masking it. And of course as with all hacks - it may break in future versions.
myNavigator._isRunning = false;
UPDATE:
Here are the two updated pens which you gave in the comments:
https://codepen.io/IliaSky/pen/YWOOkW?editors=1010
https://codepen.io/IliaSky/pen/QEVVGm?editors=1010
Basically you were adding the handlers on init event, which is fired whenever a page is added. so with your logic you are adding more and more handlers with each page. Just make sure you add them only once and you will be fine.
Add things like:
if (e.target.id == 'pagename') ...
or simply
$(document).on("init", '#dashboard_page', function(){ ... }
Take a look at .one() from jQuery - the event handler will only execute once per element in order to prevent the error: Uncaught (in promise) pushPage is already running
$(".tile_handler").one("click", ".imalink", function () {
var link = $(this).data().href;
if(link != null){
document.querySelector("#myNavigator").pushPage(link, { animation: "slide-ios" });
}})
I load a part of my basketpage inside an accordion div in my header. This works great and shows my basket in a nice dropdown.
The last problem I need to solve with this is to get the buttons in the loaded content to work. Is it possible to write an callback that make these works? Im not sure even what to google for this one..
This is how the buttons is setup in the loaded content:
checkout
Script Im using to load the content:
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox');
use the callback function of .load().
$('.dcjqg-accordion ul.sub-menu').load('/m4n?seid=etailer-basket div#centerbox.itembox.centerbox', function() {
$("#_ec_oie2").on("click", function() {
if (UI.pb_boolean(this, 'click')) { }
return false;
});
});
checkout
You need to use a child selector for the event. You can attach an event to the .sub-menu element that will fire on the content loaded in through the ajax. Something like the following could work:
$(".dcjqg-accordion ul.sub-menu").on("click", ".action.actionbasket.checkout", function() {
if( UI.pb_boolean(this, 'click') ) {}
return false;
});
Notice the second parameter to the on method. It is a selector that will be used to look at the target of the click event. I used .action.actionbasket.checkout since that is what is on your a tag.
This code may not work exactly, but this should help get you in the right direction.
Here is the link to the jQuery documentation for the on method: https://api.jquery.com/on/
I have the following to snippets of code:
$(document).ready(function() {
document.head.appendChild(
$('<script />').attr('src', 'source.js').on('load', function() {
...
})[0]
);
});
This will fire the load handler.
Whereas using the normal jQuery append():
$(document).ready(function() {
$('head').append(
$('<script />').attr('src', 'source.js').on('load', function() {
...
})
);
});
This will not fire the load hander.
What am I missing: why does jQuery append() not work?
Is using document.head.appendChild() a bad idea?
NOTE: I can't use $.getScript(). The code will run on a local file system and chrome throws cross site script errors.
Update
Some people had trouble reading the compact style, so I used extra line feeds to clarify which objects where calling which methods. I also made it explicit that my code is inside a $(document).ready block.
Solution
In the end I went with:
$(document).ready(function() {
$('head')[0].appendChild(
$('<script />').attr('src', 'source.js').on('load', function() {
…
})[0]
);
});
I think #istos was right in that something in domManip is breaking load.
jQuery is doing some funny business in its DOM manipulation code. If you look at jQuery's source, you'll see that it uses a method called domManip() inside the append() method.
This domManip() method creates a document fragment (it looks like the node is first appended to a "safe" fragment) and has a lot of checks and conditions regarding scripts. I'm not sure why it uses a document fragment or why all the checks about scripts exist but using the native appendChild() instead of jQuery's append() method fires the event successfully. Here is the code:
Live JSBin: http://jsbin.com/qubuyariba/1/edit
var url = 'http://d3js.org/d3.v3.min.js';
var s = document.createElement('script');
s.src = url;
s.async = true;
$(s).on('load', function(e) {
console.log(!!window.d3); // d3 exists
$(document.body).append('<h1>Load fired!</h1>');
});
$('head').get(0).appendChild(s);
Update:
appendChild() is a well supported method and there is absolutely no reason not to use it in this case.
Maybe the problem is when you choose DOM appendChild, actually you called the function is document.on('load',function(){});, however when you choose jQuery append(), your code is $('head').on('load', function(){}).
The document and head are different.
You can type the code below:
$(document).find('head').append($('<script />').attr('src', 'source.js').end().on('load', function() {
...
}));
You should probably make sure that the jquery append is fired when the document is ready. It could be that head is not actually in the dom when the append fires.
you don't have to ditch jquery completely, you could use zeptojs. Secondly, I couldn't find out how and why exactly this behavior is happening. Even though i felt answer was to be found in links below. So far i can tell that if you insert element before definig src element then load won't fire.
But for manual insertion it doesn't matter. (????)
However, what i was able to discover is that if you use appendTo it works.
Code :http://jsfiddle.net/techsin/tngxnkk7/
var $ele = $('<script />').attr('src', link).load(function(){ abc(); }) ).appendTo('head');
New Info: As is understood adding script tag to dom with src attribute on it, initiates the download process of script mentioned in src. Manual insertion causes page to load external script, using append or appendTo causes jquery to initiate downloading of external js file. But event is attached using jquery and jquery initiates download then event won't fire. But if it's the page itself initiates the download then it does. Even if event is added manually, without jquery, adding via jquery to dom won't make it fire.
Links in which i think should be the answer...
Append Vs AppendChild JQuery
http://www.blog.highub.com/javascript/decoding-jquery-dommanip-dom-manipulation/
http://www.blog.highub.com/javascript/decoding-jquery-dommanip-dom-manipulation/
https://github.com/jquery/jquery/blob/master/src/manipulation.js#L477-523
http://ejohn.org/blog/dom-documentfragments/
I have the following in my javascript file:
var divId = "divIDer";
jQuery(divId).ready(function() {
createGrid(); //Adds a grid to the html
});
The html looks something like:
<div id="divIDer"><div>
But sometimes my createGrid() function gets called before my divIder is actually loaded onto the page. So then when I try to render my grid it can't find the proper div to point to and doesn't ever render. How can I call a function after my div is completely ready to be used?
Edit:
I'm loading in the div using Extjs:
var tpl = new Ext.XTemplate(
'<div id="{divId}"></div>');
tpl.apply({
});
You can use recursion here to do this. For example:
jQuery(document).ready(checkContainer);
function checkContainer () {
if($('#divIDer').is(':visible'))){ //if the container is visible on the page
createGrid(); //Adds a grid to the html
} else {
setTimeout(checkContainer, 50); //wait 50 ms, then try again
}
}
Basically, this function will check to make sure that the element exists and is visible. If it is, it will run your createGrid() function. If not, it will wait 50ms and try again.
Note:: Ideally, you would just use the callback function of your AJAX call to know when the container was appended, but this is a brute force, standalone approach. :)
Thus far, the only way to "listen" on DOM events, like inserting or modifying Elements, was to use the such called Mutation Events. For instance
document.body.addEventListener('DOMNodeInserted', function( event ) {
console.log('whoot! a new Element was inserted, see my event object for details!');
}, false);
Further reading on that: MDN
The Problem with Mutation Events was (is) they never really made their way into any official spec because of inconcistencies and stuff. After a while, this events were implemented in all modern browser, but they were declared as deprecated, in other words
you don't want to use them.
The official replacement for the Mutation Events is the MutationObserver() object.
Further reading on that: MDN
The syntax at present looks like
var observer = new MutationObserver(function( mutations ) {
mutations.forEach(function( mutation ) {
console.log( mutation.type );
});
});
var config = { childList: true };
observer.observe( document.body, config );
At this time, the API has been implemented in newer Firefox, Chrome and Safari versions. I'm not sure about IE and Opera. So the tradeoff here is definitely that you can only target for topnotch browsers.
To do something after certain div load from function .load().
I think this exactly what you need:
$('#divIDer').load(document.URL + ' #divIDer',function() {
// call here what you want .....
//example
$('#mydata').show();
});
Through jQuery.ready function you can specify function that's executed when DOM is loaded.
Whole DOM, not any div you want.
So, you should use ready in a bit different way
$.ready(function() {
createGrid();
});
This is in case when you dont use AJAX to load your div
inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like
<div id="div1">
<script>
$(document).ready(function(){
//do something
});
</script>
</div>
and you can do the same to other divs that you have.
this was suitable if you loading your div via partial view
I have the following problem: on a customer's homepage the navibar is loaded by javascript, but I need to change some URL's on it. If I just start my script on $(document).ready() it runs before the customers script and has no effect. I only can use setTimeout for my function to wait until the other script is ready, but it's not good or safe at all. I can't change anything on the website, only add a javascript - is there a way to time it after the other one?
You can use repeated setTimeout, in order to check if menu is accessible.
function check_menu(){
if(document.getElementById('my_menu')==null){
setTimeout('check_menu()',500);
} else {
//do some stuff
}
}
If you have information about the menu like the id or class, use the onLoad() jQuery method on the element. For example if the code is loading asynchronously, and you add the onload to one of the last elements it should fire after the content has finished.
$.post('AsyncCodeLoad.php', function(data) {
$('#lastElementToLoad').onLoad(RunMyFunction);
});
Or if you have no chance to insert your code into the async loading just add to the bottom of the </body>:
$('#lastElementToLoad').onLoad(RunMyFunction);
Just a thought.
Yes, add your script at the bottom of the <body /> tag to ensure it does not run until all other scripts have run. This will only work however if your customer is loading the nav links synchronously.
If the nav is being loaded asynchronously, use JS's setInterval to repeatedly check the contents of the nav for links. When you determine the links have been added, cancel your interval check and call your script's logic entry point.
Cheers
Fiddle: http://jsfiddle.net/iambriansreed/xSzjA/
JavaScript
var
menu_fix = function(){
var menu = $('#menu');
if(menu.length == 0) return;
clearInterval(menu_fix_int);
$('a', menu).text('Google Search').attr('href','http://google.com');
},
menu_fix_int = setInterval(menu_fix, 100);
HTML
<div id="menu">Bing Search</div>