jQuery Mobile $.mobile.changePage() - javascript

I have a problem regarding $.mobile.changePage(); I have this select control that serves as a Jump To Page controller. The code is written below:
$( document ).one( "pagechange", function() {
$("#jumptopage").bind("change", function(){
var val = $(this).val();
$.mobile.changePage( "http://localhost/mchild/dashboard/videos/all/20/" + val, {reloadPage : "true",transition: "fade", allowSamePageTransition : "true"} );
return false;
});
});
Now this code works the first time; but as I jump to another page it causes jQuery Mobile to jitter back and forth to current page and previous page that was loaded before, or in other cases the bind() wont work anymore.
I tried to log the activity by adding
console.log('i was triggered')
inside the $( document ).one().... right after the bind statement and it still fires except for the bind.
I'm not sure if I did something wrong... please help...

Related

Scrolling to an element without ID in a window opened by window.open

At the top of my page, I have a menu with a couple of items, and when I click them, I scroll to a point of in page where the div is placed, using this line of code:
$('html, body').animate({scrollTop:$(divid).position().top - 160 }, 'slow');
where $(divid) contains the classname of the div. (I am using Drupal so the possibility of adding an ID is not there).
This works fluently, but now I have the same menu in another page. When I click a link, I navigate to the page where the div is placed in, but I can't get it to scroll to the div.
After a lot of research I came to this piece of code
$('#block-views-footer-menu-block-2 .views-row-6 a').click(function(e){
e.preventDefault();
var newwindow = window.open('/aanbod', '_self');
$(newwindow.document).ready(function(){
to_position('.field-paragraphs:nth-of-type(6)');
});
});
where to_position() contains the first line of code in this post.
However, the to_position() function fires before the new window is loaded. This way, the moment the to_position() function is fired, '.field-paragraphs:nth-of-type(6)' is not known yet, so the function cannot access the position of it.
I really don't see what I am doing wrong, any help is appreciated.
Thanks in advance!
Pass the information to the pop-up itself and let it do the scrolling for you.
var newwindow = window.open('/aanbod?scrolltoposition=' + ".field-paragraphs:nth-of-type(6)", '_self');
now in this new window, add the code to scroll the position you want to scroll to
$(document).ready( function(){
var elementSelector = location.search.split( "=" )[1];
var $element = $( elementSelector );
$('html, body').animate({scrollTop:$element.position().top - 160 }, 'slow');
} );
ensure that you have included the jquery in the pop-up
If you are using jQuery, you may use the following
$(document).ready(function(){
// your code
});
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

Get current URL from document.ready

I am trying to parse my URL in document.ready() so that I can get the id of the current page and dynamically populate the page with results from an AJAX call. The problem I am running into is due to the fact that I think that 'document.URL' references the previous page until 'document.ready()' has fully executed.
How do I get around this? I have researched document.load(), and auto-refreshing the page once, but I cannot seem to get this to work. I have been working on this since yesterday.
Here is my code:
$( document ).ready( function(){
var id = document.URL.substring(document.URL.lastIndexOf('?')+4);
if(!loadObject.executed) {
loadObject(id);
loadObject.executed = true;
} else {
$('#page-full').on('pagecreate', loadObject(id));
}
});
Try to use document.location.href instead of document.URL.
Hope this helps.

jQuery Mobile page loads, but buttons doesn't works

I've solved my last issue in this topic: jQuery on second click doesn't work - mobile
I have two pages, index.php and add.php.
From index.php I call the page add.php this way:
$(document).on('pagebeforeshow', '#page-index', function(){
$('#openAdd').bind('click',function(){
$.mobile.changePage('add.php');
});
});
I have several buttons on the page add.php that work, but if I hit the button "openAdd" from the page Index which opens the page add, every single button on the page add stops working. I get no errors, no messages, nothing, simply it doesn't perform any action.
If I type in the browser the URL directly to mywebsite.com/add.php they work.
This is what I've tried so far without any success:
<input type="button" id="clients-btn" value="Clients" data-role="none"/>
$("clients-btn").on("click", function(){
console.log("hit!!!!");
});
$(document).on('pagebeforeshow', '#page-add', function(){
$('#clients-btn').bind('click',function(){
console.log("hit!!!!");
});
});
Solved.
All you have to do is, on the second page (in my case add.php), put the following:
$('#page-add').on("pageinit", function () {
$('#clients-btn').one('click', function () {
console.log('button clicked!!');
});
});
Edit: actually not working.
Wrap your whole code in pagecreate
$( document ).on( "pagecreate", "#page-add", function( event ) {
$('#page-add').on("pageinit", function () {
$('#clients-btn').bind('click',function(){
console.log("hit!!!!");
});
});
});
And try adding code called at the end of page

js / jquery function call order not reflected in result

EDIT:
Alright, to help resolve this, I've put up the example online:
http://lodge323.com/test/index.html
The example works as intended, but it doesn't have the content that I want on it. Note that this apparently only happens on FF13 and not IE9.
Steps to recreate the problem:
-Ctrl+F5 to reload the page (overriding cache).
-Using Firebug (addon for FF), change 1.jpg to head.gif
-Click on the Inventory menu tab on the right
Notice how there's a gap between the menu and the bottom which doesn't happen if 1.jpg is used. So question is, how can I get that gif image to work properly with the page?
jQuery's load is asynchronous.
Instead of calling loadSidebar after loadContent, pass it as a callback to load:
$(document).ready(function() {
$(".tabs a").click(function() {
loadContent('#ContentDiv', this, '.tabs a', 'id', loadSidebar);
});
});
function loadContent(divTarget, elm, selector, attr, callback) {
$(divTarget).load($(elm).attr(attr) + ' #ContentLoad', callback);
}
This will call loadSidebar, when the content has finished loading, instead of immediately after it starts loading.
Check out Understanding Callback Functions in Javascript. It might help you understand why the callback is needed.
Edit
As Eric pointed out it the comments you are also storing a url in an id. You should instead store it in the href attribute of the anchor. Then you can just return false from your click handler to avoid the entire page being loaded:
$(document).ready(function() {
$(".tabs a").click(function() {
loadContent('#ContentDiv', this, '.tabs a', 'href', loadSidebar);
return false;
});
});

Dont understand why this javascript won't work in jQm

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){

Categories