Javascript AJAX on a dynamicly loaded div? - javascript

How to add onload event to a div element?
I've read this, despite this I have a problem..
I know there's no onLoad for divs, but I should be able to execute a snippet like so:
...
<div id="content">
<div class="text">
</div>
</div>
<script type="text/javascript">
navigate('main.php', 'content');
</script>
....
This doesn't work, if I start a new browser session and navigate to index.php, it shows me a login window. After logging in it redirects me to index.php but with some session variables and cookies set. Now index.php contains the code above, prior to this content didn't exist.
Now to my issue: it appears as if most browsers refuses to accept that content exists,
in the navigate function I've got:
function navigate(str, what) {
if(what == null) {
what = document.documentElement;
} else {
what = document.getElementById(what);
}
what will become null because it's a not a valid Element at the moment of execution.
I've tried:
window.onLoad = naviate('main.php', 'content');
Which does nothing, same issue there..
Also tried putting the <script> block at the end without luck.
I can't use jQuery or anything so please keep it to standard Javascript, HTML and CSS.
Browsers in use: IE8, Chrome, FireFox.
Load index.php
Login to loginwindow
Load index.php
Upon completed load of index.php, read all elements including content
Update content with some AJAX data.
It works if
I login, load the page once with unsuccessful result and then refresh the page again.
And here's the reason why:
I use AJAX on the login window as well, it uses navigate() just as all my buttons and what not does. So the issue is that index.php gets loaded, with a login window, that login window updates the entire page with AJAX (javascript) which in turn, tries to call navigate() again from within the return data from the AJAX call...
The "inline" navigate() gets called!!!, it's just that it doesn't know all the elements because it's load via AJAX.

Try this :
window.onload = function(){
navigate('main.php', 'content');
}

According to my tests you can get div element by .getElementById even before the page is loaded.
Do not forget that the navigate function must be defined before it is called. So if you have your scripts at the end of document (which is correct), you must call the function after execution of theese scripts.
But anyway, you've assigned the .onload function wrongly. Do it like this:
window.onload = function(event) {
/*any script here*/
}
Or like this:
function load(event) {
/*any script here*/
}
window.onload =load;

Related

how to load an external js file after a page loads and use a function from it

I need to load an external js file into a html file AFTER the page loads. This is because in this external js file a variable only updates itself after the html file loads.
that being said i also need to use the function showScreen afterwards. showScreen is a boolean in the external js file.
I only want it to switch screens when showscreen is true and that can only load after the html file loads. So right now if i did window.onload = showScreen in the html, it is always undefined
external.js ( this is part of the external file and the function Im trying to use)
function showScreen(showTraditionalScreen) {
console.log("showTraditionalScreen "+ showTraditionalScreen);
return showTraditionalScreen;
}
UPDATE:
index.html (this is the bottom half of the file where i want to make the changes)
<script src="js/main.js"></script>
<script src="js/additions.js"></script>
<script src="../server/webcam.js" defer></script>
<script>
if(window.onload =showScreen)
window.location.href = "traditional.html";
}
</script>
</body>
</html>
it currently doesnt do anything, but the point is, when showScreen is true the page will change to traditional.html. Currently it doesnt do that
this file is also asynchronous, so the console.log continues to print true or false
I know ajax is a good option and i have been experimenting but im still a little lost.
how do i use the external.js function in an html file after the page loads?
Why isnt my file currently allowing me to use showscreen?
you can use defer
<script src="path" defer></script>
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. The defer attribute is only for external scripts (should only be used if the src attribute is present).
wrap the function call in a window.onload
It looks like if(window.onload = showScreen) might be checking if the assignment to the onload variable happens, as opposed to checking that the return of showScreen is true. Is that your intention? I think this will return true before the page finishes loading (if it succeeds), so it's not useful as a way to check that the page has loaded if that's what you wanted.
Your showScreen function takes a parameter. When you assign a function like this to onload the way you've done, you're passing in a single default 'event' parameter. If that's what you wanted, maybe that's what you mean by "This is because in this external js file a variable only updates itself after the html file loads."?
I also think you're missing an opening bracket at the end of the first line of the if statement, so that could be causing problems.
Here's another stab at providing what you want. In the following code, I'm waiting for the page to load, and once it has I'm checking to see if the showScreen function returns true. Assuming you needed the page load event as a parameter, I've passed that through to your showScreen function. Otherwise I'm not sure where the showTraditionalScreen param is coming from.
<script>
window.onload( function(event){
if(showScreen(event)) {
window.location.href = "traditional.html";
}
});
</script>

Javascript From Console - Load a Few Pages, Then Run Function Per Page Load [duplicate]

I'd like to be able to call a jquery function once window.location has completed loading a URL. Is this possible? I can't seem to find anything online about this.
for instance:
if(parseInt(msg.status)==1) {
window.location=msg.txt;
alert("This URL has finished loading")
}
Thanks,
-Paul
You can either use window.onload of the destination page (if you have access to modify the code of that page), or you can use window.onunload to have the alert be launched when unloading the current page. You cannot execute code on the current page after the new page has been loaded.
Yes.
This page demonstrates onload/onunload behavior.
<html>
<head>
<script>
window.doUnload = function(){
alert("Here!");
}
window.doLoad = function(){
window.location="http://www.google.com";
}
</script>
</head>
<body onload="doLoad();" onunload="doUnload();"></body>
</html>
After a user logs in for the first time I need to load my index page to initialize everything but then need to forward them to another page for profile completion.
use window.location to redirect the user to your index, adding a query parameter (something like window.location=index.php?firstLogin=true ) and on your index redirect (using javascipt http 300, header() or whatever you are using) to the profile page after it ends loading if the parameter is set
Iframe
One (ugly) method you could use is to instead of using window.location, clearing the body, adding an iframe with the relevant path and listening to its onload function.
After that you can run code inside the iframe as long as it's not cross-site scripting.
I use this method to perform small automated scripts, that can't really on third-party plugins.
Ajax
Another method might be using ajax to load the page/body content. Then replacing your body with the newly loaded body and start executing the next functions.

Using $.getScript (jquery): code is not executed

I am working on updating my website, which now uses an AJAX engine. My engine works well, up-to-hand for some reason some pages do not execute javascript, let me explain: when the anchor change I use $.get for data recovery. The pages have this structure:
title
h1
script1.js,script2.js,etc.js
style1.css,style2.css,etc.css
<!--there's the page's content-->
It appears reload the page solves the problem, but i don't understand what is different. In the previous code, the engine runs successfully, reloaded or not:
$.getScript("script1.js");
$.getScript("script2.js");
$.getScript("etc.js");
In addition, a php generated script contains user's current state under an Object form:
$(function(){
user = new Object();
user.id = user.logged = <?php echo $user->getId();?>;
user.nick = "<?php echo $user->getNick();?>";
user.mail = "<?php echo $user->getMail();?>";
user.logout = function(){
};
});
The $.getScript request is successful, but the user object is not changed. The script, however, has yet been modified. And it don't works from console too.
The update is currently online at v2.wawolf.com, you'll find everything you need.
Hotlink: Engine's code
I just solved my problem: when all document is loaded, $(function(){}) will not work again, so calling a script which uses $(function(){}) will no get run. I removed it from all my secondary-called scripts and now all works perfectly!
it might just be a loading order issue.
try encapsulating the JS loading in an onload function
$(window).load(function(){
//get script loads here
}
or
$(document).ready(function() {
//get script loads here
}
Sometimes I use one inside the other for dynamic JS script that needs to be loaded last.

Is there a way to load a function from the htm that you're loading with .load()? JQuery

In my main window main.htm I have a div button that loads another htm file into a large div when clicked. I use .load() to achieve this:
$('#mainpanel').load("search.htm");
There is a function in "search.htm" called test() which only consists of alert("hi"); and I want this to load when search.htm is loaded into the div. I used the body onload tag and window.onload = test; and even $( document ).ready() but nothing works. It only works if I access search.htm on its own, but if I access it through main.htm it does't alert "hi". Is there a way to use .load() to load the page and a function? or is there a way to get the function the onload when I select the div that loads the page?
The onload / document ready will only fire once (when the parent document is loaded)
Either add a
<script type="text/javascript">
test();
</script>
to the end of the search.htm (so it's executed after everything else in the page has been parsed) or call test(); from the parent page after the load completes (via a callback)...
$('#mainpanel').load("search.htm", function(){
test();
});
It depends which page you want to be responsible for executing the function. In the latter case, the parent page needs to know the name of the function in search which may or may not fit your design.
Using window.onload or $( document ).ready() doesn't make sense because the document is most likely already loaded when you run that function.
You can pass a callback to .load and access the function inside there. The callback is executed when the other page is loaded:
$('#mainpanel').load("search.htm", function() {
test();
});
Of course test must be in global scope for this to work.
As always, it's advisable to the read the documentation of the methods you are using: https://api.jquery.com/load/.

How to wait until a web page is loaded with javascript?

I want to change between two pages in html with javascript, but when I change with window.location, the code that is after this sentence continues executing.
So when I do, for example, a call to getElementById() it doesn't recognize the element because the page is still loading.
function myFun(){
// ...
window.location = 'page.html';
// ... wait until page.html is loaded
}
How can I wait until the page is loaded to avoid this problem?
When you do
window.location = 'page.html';
you replace the page in the browser, the one containing the code of myFun, by a new page. There is no way for the code following this instruction to be executed.
If you want to execute it, and only after that change page (but I don't see the point), then you might do
document.onload = function(){ window.location = 'page.html'; };
You can use jQuery document.ready or you can create custom bind like this one. In case you use jQuery.
$(document).ready(function() {
window.location = 'page.html';
});
You can't execute code in your own page after doing window.location = 'page.html';. Your page will be replaced by the new page and the code in the current page will no longer be there.
The only ways to execute some code after page.html is loaded into the current window are as follows:
Load it in an iframe or another window and monitor for when the iframe or window has finished loading. In this way, your current code stays around and is not replaced.
Have some code in page.html that monitors when it finishes loading and trigger your desired action from there.

Categories

Resources