Execute javascript after page transition - javascript

I am trying to create an dynamic phonegap app using jquery mobile but am having some issues loading javascript when going to a page using transition.
My index page look like this:
<body>
<div data-role="page" id="homePage">
<div data-role="header" data-theme="c" data-position="fixed">
<h1>My Page</h1>
</div>
<div data-role="content" id="pageName">
<ul data-role="listview">
<li>This is a test</li>
</ul>
</div>
</div>
</body>
On my "pages/clubpage,html" I have included below in the head:
$(document).on('pageshow', function (){
alert("I am here!");
});
Somehow I don't get the alert? What am I doing wrong?
Please help and thanks in advance :-)
<------- EDIT --------->
I am actually trying to goto page 2 and that page has an dynamicly generated listview like this:
$(document).on('pageshow', '#clubPage',function (){ // GET THE CURRENT CLUBPAGE //
var clubid = getUrlVars()["clubid"];
$.getJSON("http://mypage.com/groupmenu.php?callback=?&userid="+userid+"&clubid="+clubid,
function(data){
var content = []
$.each(data , function(i,val){
content.push(val.list);
});
$("#mathes_list_count").html(content.join(""));
$('#mathes_list_count').listview('refresh');
});
});
Now my question is... Can I generate this before the transition is made?

You are not getting anything because delegated page events needs 2 objects, one original like document and a second one, same one you are missing. In your case it is a page id:
$(document).on('pageshow', '#homePage',function (){
alert("I am here!");
});
But this isn't your real problem.
To understand this situation you need to understand how jQuery Mobile works. It uses ajax to load other pages.
First page is loaded normally. Its HEAD and BODY is loaded into the DOM, and they are there to await other content. When second page is loaded, only its BODY content is loaded into the DOM.
Read more about it here in my other answer, you will also find solutions and examples: Why I have to put all the script to index.html in jquery mobile
EDIT :
There are two possible solutions here. You can executed getJson on a page before, store its content and rebuild it on an another page during the pagebeforecreate event. Take a look at my other answer how you can store data between transitions, search for topic Data/Parameters manipulation between page transitions : jQuery Mobile: document ready vs page events.
Or you can initialize page transition and load/build all data during the pagebeforecreate or pageinit event. Which is still better then doing it during the pageshow event.
In my opinion, solution 1 is a better solution because transition wont suffer and data will not magically appear if pageshow event is used.

Related

Add/Remove classes from navigation loaded with Jquery

I am loading in the content of my sidebar navigation with jquery from a nav-content.html file so I don't have to update it on every page each time it updates.
What I am trying to do is when on a specific page, the sidebar nav with uncollapse based on what category that page is on.
I am trying to target elements in that loaded nav to be active when on certain pages and it only works when the nav is hard coded into the page's html but it doesn't work when I load it in from the nav-content.html file with jquery.
I did noticed when i view the source code on browser it doesn't actually paste in the html but still displays it which I think is the disconnect but I am not 100%. Not sure if I should look into different way to load it in or if my jquery is the issue.
Any insight would be greatly appreciated.
HTML:
<nav>
<div id="sidebar">
<div id="sidebar-content">
<!-- nav loads here from nav-content.html -->
</div>
</div>
</nav>
Jquery:
/*Loads the Nav */`
window.onload = function(){
$.get("nav-content.html", function(data){
$("#sidebar-content").html(data);
})
}
/* changes classes within the loaded nav based on what page it's on */
$(document).ready(function() {
$('ul#devSubmenu').removeClass('collapse'),
$('ul#appStackSubmenu').removeClass('collapse'),
$('a[href^="#devSubmenu"]').attr("aria-expanded","true"),
$('a[href^="#appStackSubmenu"]').attr("aria-expanded","true");
});
I asked this a few days ago but this is a rephrased/re-explained of deleted post.
Two things to get you on the right path.
1) jQuery's get() does not load an HTML file. You might mean to use load() to get your sidebar content: https://api.jquery.com/load/
2) $(document).ready fires before window.onload. See: window.onload vs $(document).ready()
In order to ensure that your content is loaded before modifying the classes, you can make your modifications in the callback from load() (the function passed as the second parameter to load()).
Something like [untested]:
$(function() {
$( "#sidebar-content" ).load( "nav-content.html", function() {
$('ul#devSubmenu').removeClass('collapse'),
$('ul#appStackSubmenu').removeClass('collapse'),
$('a[href^="#devSubmenu"]').attr("aria-expanded","true"),
$('a[href^="#appStackSubmenu"]').attr("aria-expanded","true");
});
});
The wrapping $(function() { ... }) is just jQuery shorthand for $(document).ready();

document ready fires too early?

It is kind of theoretical question as it can't be checked right away. The problem is about the possible reasons why the jQuery code doesn't work, however it is loaded on the page now. Also, it DOES what it has to do right after the page is loaded and I copy-paste this script code from the source of the loaded page into the console.
<body>
<div id="id1">...</div>
<div id="id2">some html code goes here... </div>
<script>
jQuery(document).ready(function() {
var el = jQuery("#id1");
var var1 = el.width();
el.css({'margin-top':'10px','margin-bottom':'20px'});
jQuery("#id2").css('margin-top', var1+'px');
});
</script>
<div>and here... </div>
</body>
P.S. The jQuery library is loaded. There are no errors in the Chrome console. The script is in the body tag.
P.P.S. Can it be because of #id1 (contains ) is loaded from another site so document ready fired earlier? Is that exactly the reason?
Any other possible reasons?
Unfortunately, it is hard to check it right away as the access to that page is limited and takes several steps to update by other persons that can't be accessible right away.
However, the possible solution is needed right away.
Added id1 and id2 into the html code.
use window.onload is most often used within the element to
execute a script once a web page has completely loaded all content.
jQuery(window).load(function () {
var el = jQuery("#id1");
var var1 = el.width();
el.css({'margin-top':'10px','margin-bottom':'20px'});
jQuery("#id2").css('margin-top', var1+'px');
});

jquery .load() function only working the first time

So I have a website I am working on just as a personal website that uses jQuery and jQuery UI
Previously I have been using hidden html code and just using jquery to show it.
But its making my html file messy so I wanted to use jquery's .load() to do the same thing but from an external file.
Right now, its set to a .click function.
For my hidden html it shows it every time when I click a particular element.When you click on a different element it. It hides the first one. I am doing it by having a div with 2 classes. The problem is when I tried to load html into a hidden div, and then show it and hide it, it only worked the first time.
Enough talk, here is my code. #1 works , #2 only works on the first click. And leaves imagearea blank every time after.
$(".jquery").click(function(){
clearImageArea();
hideThumbnails(5);
showThumbnails();
$("#1").click(function(){
$(".imagearea").html(js);
$(".jscode").show(1000);
$(".title").text("Extending jQuery");
});
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html");
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
now my hidden stuff in my html file
First my html and js code is loaded into here from jqueryEx.html and is being hidden elsewhere in my javascript via $(".hidden").hide(); and loaded then into into imagearea via .html() and shown via .show()
<div class="jquery2 hidden">
</div>
My other div looks like this which is put into imagearea by clicking on #1
<div class="jscode hidden">
<div class="block">
//lots of js code escaped out into html
</div> <!-- end of block-->
</div>
elsewhere in my JS code at the beginning I have var js=$(".jscode"); to load it into the js variable you saw earlier.
if you want to see an out of date example of what I am working on
go to www.3realsoft.com (only cs and js work on skills)
if you want to see any additional parts of my code, just ask. Most of it is there on my website though.
I got to this item in my search results, when I was trying to have a button both load and refresh the content, and the load was working but the refresh was not working.
Here's a shorter version of the solution, setting Cache to false was the key. Solution found over at this other link, but I'm posting this concept here because if Google dropped me in this item, others looking for the same will also probably find themselves here. Props to John Millikin, make sure to go over to his answer and upvote him: Stop jQuery .load response from being cached
<script type="text/javascript">
$(document).ready(function () {
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
$('.detail-expand').click(function () {
var detailRowElement = $(this).closest('.session-row-tr').next();
var detailElement = detailRowElement.find('.detail-row-div');
var sessionId = detailElement.data("sessionId");
detailElement.empty();
detailElement.load('/Admin/WebLogPartial/' + sessionId, function () {
$.bootstrapSortable(true, 'reversed');
});
detailRowElement.show();
});
});
</script>
Anything that depends on the HTML being loaded must be done in the callback function, because the first A in AJAX stands for asynchronous.
$("#2").click(function(){
$(".jquery2").empty();
$(".jquery2").load("jqueryEx.html", function() {
var jquery2 = $(".jquery2");
$(".imagearea").html(jquery2);
$(".jquery2").show(1000);
$(".title").text("Extending Jquery Example");
});
});
I'm not really sure what you're trying to do with .html(jquery2), since the argument to .html() is supposed to be a string, not a jQuery object. Maybe you meant:
var jquery2 = $(".jquery2").html();

loading a webpage into a div-not getting loaded

I'm trying to load a webpage into a div...But It's not getting loaded into the div...instead it's loading as a whole webpage....why??
<li>About Us</li>
<div class="bdy"></div>
javascript code:
function AboutUs () {
// body...
//$('.bdy').load('http://www.jhsoftech.com' );
$('.bdy').html('<object style="width:100%;height:435px;" data="http://www.erail.in">');
}
I opened your site in an iframe sandbox.
JSFIDDLE Example
$('.bdy').html('<iframe sandbox="allow-scripts" style="width:100%;height:435px;" src="http://www.erail.in"><iframe>');
})
The problem with your site, setting another location / redirecting the page is this part of code on the your site:
if(top!=self)top.location.href="http://erail.in";
Remove this and you are able to implement it without a sandbox preventing allow-top-navigation.
Just change to
<div class="bdy"></div>
And use jquery take a look at this one http://jsfiddle.net/markipe/TEHsJ/

Javascript Error onload image fadeIn

I am getting an inconsistent error with my script. Often times everything works fine, however, every now and then I am getting the following error: ReferenceError: fadeIn is not defined
Here is the relevant code:
In the <head>
<script type="text/javascript" charset="utf-8">
window.fadeIn = function(obj) {
var item = $(obj).parent();
item.fadeIn(1000);
}
</script>
In the <body>
<div class="item" style="display:none"><img onload="fadeIn(this)" src="/uploads/thumbs/{{image.url}}"><br>{{ image.description }}</div>
Again, The images are loading and fading in most of the time but every now and then I get the error and the images do not fade in.
Is there a better way to approach this? Or just something I'm missing?
You need to make sure your code is loaded after the DOM is ready.
window.onload = function(){
var fadeIn = function(obj) {
var item = $(obj).parent();
item.fadeIn(1000);
};
};
... that's a partial fix, but not really, because in all likelihood, your <img/> tags with the onload hardcoded into them is going to try to fire that method before it's available.
Since you're using jQuery anyhow, you should look at something like this:
$(function() {
$(".item img").load(function(){
$(this).fadeIn(1000);
});
});
and get rid of the hardcoded onload from your img tags.
It should be noted, also, that there are caveats listed on the .load() API page:
From the docs (http://api.jquery.com/load-event/):
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
A better solution might be to hide the images with CSS, then after the load event is fired, fade them in.
(Even better than that might be to let browser behavior be, as your results may be mixed, and users seeing a blank page might instead hit the reload button thinking their browser glitched, before your animations are complete. ... just a friendly warning that these kinds of DOM manipulations can sometimes have unintended side-effects on user behavior!)
You can try defining the Handler directly in the Script instead of assigning it in HTML..
Javascript
<script type="text/javascript" charset="utf-8">
$(function() {
$('img').load(function() {
var item = $(this).parent();
item.fadeIn(1000);
});
});
</script>
HTML
<div class="item" style="display:none">
<img onload="fadeIn(this)" src="/uploads/thumbs/{{image.url}}">
<br>{{ image.description }}</div>
You're missing a document ready, so jQuery is'nt loaded, and the fadeIn function is'nt defined. Even if the image is loaded, there is no guarantee that jQuery is loaded aswell.
You're also actually calling your function fadeIn, while jQuery already has a function called fadeIn, and even though they have a different namespace it does seem like a bad idea to me.
nPlease ensure you have correct link to JQuery javascript file. You can use Google's hosted library for an example or create your own copy of this .js file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
min.js file can be found at download section of JQuery official website. Save it and place into the website folder. And link it like:
<script src="/js_folder/jquery-1.8.2.min.js"></script>
Another option with Jquery:
<div class="item" style="display:none">
<a href="http://docs.jquery.com/">
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif">
</a>
<p>image name</p>
</div>​
Script:
<script type="text/javascript">
$(document).ready(function() {
$('.item').delay('1000').fadeIn('1000');
​ });​
</script>
http://jsfiddle.net/CYGNp/1/

Categories