document.onload not working for me? - javascript

Well I'm simply playing around with a userscript of GreaseMonkey and here's just something simple I attempt to do;
function test() {
document.getElementById('elementhere').innerHTML = 'test';
}
document.onload = test();
It works if I go to the page I want to use it on and do "run" or "reload & run" - but it won't run automatically, which I'm trying to make it do by using document.onload.

What you need is:
window.onload = function () {
// do the work after everything was loaded (DOM, media elements)
}
document.onload it doesn't exist. It works if you at least target some specific element from document for example:
document.querySelector("img").onload = function ()
{// do your thing after 'img' was loaded}
You have other options if you want to execute some code after the DOM is the only element ready without wait for media elements to load like:
Import an async script tag loading the file with the code:
You can place this tag wherever you want in DOM and it will not interrupt nothing, will load after the DOM finish to load. you should take a look to MDN documentation about that.
If you take a look again in MDN documentation they will recommend you in section Notes to use DOMContentLoaded and DOMFrameContentLoaded events which can be handling by addEventListener. So, if you do this:
document.addEventListener('DOMContentLoaded', handlerFunc);
Will work for you.
I hope this can be helpful for you...

When you write document.onload = test(), you are calling the test function, and assigning its return value to the onload handler. This is clearly not what you intended.
document.onload = test;
This will assign a reference to the test function to the onload handler. When the event fires, that is when your function will be called.

It is because you are assigning the result of the test function instead of the function itself due to the parentheses () on the last line.
Remove them and it may work.
If not then:
Apparently that is by design. [Chrome - v57]
Use document.addEventListener("DOMContentLoaded", <function_name>); instead.
See: Page lifecycle : DOMContentLoaded

Maybe do this:
<body onload="test()">
Or is that not what you're looking for? If you want to do it without the HTML bit above, maybe try and replace document with window:
window.onload = function ()
{
document.getElementById('elementhere').innerHTML = 'test';
}
I would give that a go because of this:
window.onload vs document.onload
I know that posting a link to a link is lame, but you will see why I did that (hopefully).
Cheers!

No Need to call the function on the page .. just you need to use below code which is best practices of coading
window.onload = function() {
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
}

It's working but you can use alternate
window.init = test;

If you are using Greasemonkey then you don't really need a using onload event since the Greasemoneky script is called only when DOMContentLoaded is fired.
The code in a Greasemonkey user script gets invoked when the
DOMContentLoaded event fires (during event capture as of GM 0.8.6). It
is a DOM event implemented by Mozilla, similar to window.onload.
However, since it waits only for the DOM to load, instead of the
entire page (including images, style sheets, and etc.) it happens
sooner.
http://wiki.greasespot.net/DOMContentLoaded
I think you would just need to call test() without any event listeners.

did you try this?
<body onload="test()">
or
$(document).ready(function test() {
document.getElementById('elementhere').innerHTML = 'test';
}

Related

Cant run function (create element) on page load

I use window.onload() to create a new div with text inside it. It works if I add it to a button (onclick) but it will not fire when I am using it with window.onload(). I have to other window.onload in the same js file that works well.. Any idea how I can fix this and what the problem might be?
My code:
function addDate() {
var addDiv = document.createElement('div');
addDiv.innerHTML = "test";
document.getElementById('date').appendChild(addDiv);
}
window.onload = addDate();
1)The way you're binding, you can have just one method attached to an event. You need to add an event listener for what you want.
window.addEventListener("load", function() { alert("hello!");});
Setting directly a method to the onload event will replace any previously attached method. But if you use listeners instead, you can have many of them bound to an event.
2)If you comment out the onload in your external file, when the document.getElementsByClassName("bar") is called, your document isn't ready yet, then, it will return 0 items.
3)Use the addEventListener as I explained in the first point. If you apply this in both places, it will work like a charm.
if you want more info on window.onload check it out here
When you say "I have to other window.onload in the same js file" I'm assuming you mean "I have two other...", and that would be the problem right there.
If you say:
window.onload = doThis;
window.onload = doThat;
Only doThat gets called. Also, notice... no parentheses! It's window.onload = doThat, NOT window.onload = doThat().
If you use:
window.addEventListener('load', addDate);
Then you can get the function to be called, and not mess up other functions being called.
I would suggest you use a library such as jQuery to do JavaScript work. It's much easier to deal with problems like those. The initialization makes use of the ready function.
$(document).ready(function() {
addDate()
});
You can add as many ready() calls as you need (one per script).
Under the hood, as mentioned by others, it will use window.addEventListener(<event name>, <inline function>). So we added a little bit of code, things will be a tad bit slower, but you're going to have code that works much faster.
Thanks everyone, the problem was that I was using window.onload two times in my code. And the solution, as you all said, was to use window.addEventListener instead. I also removed the parantheses.
So for anyone else getting the same problem, use window.addEventListener to trigger the code instead. Like:
window.addEventListener('load', databaseToNewElement);
window.addEventListener('load', addDate);

how can i invoke a function after page is done loading? (and only then..)

I'm having trouble with some jquery code.
in my HTML page I use ajax to get some info, and then I'm changing an HTML element
with $("#id").html(...).
The problem is, I also have a $(document).ready code which I wanna call only once
when the page is done loading, but after each change in the html with the $("#id").html(...)
the code is called once again.
How can I run the $(document).ready code only once?
Here is an example:
$(document).ready(function(){
// this code will run not only once...
}
function f(){
$("#id").html(...);
}
Try:
var run = false;
$(document).ready(function() {
if(!run) {
...
run = true;
}
});
...or...
$(window).load(function() {
...
});
The first one will make sure it is only run once; the 2nd one is run when the entire page is finished loading (useful if you need to resize things once images have finished loading).
From the comments on the .ready documentation:
Looks like .ready() fires not only when page initially has settled the
DOM, but apparently also after changes to the DOM. This is an issue if
your ready handler changes the DOM. That will result in ready() firing
more than once. It may result in an endless loop if each invocation
adds yet more to the DOM. Firefox and IE behave differently to this,
including different error messages, and leaving the page display in
different states. So, if ready() modifies the DOM, then it would be
wise to have a way to check whether ready has already been fired.
Replying to self: Well it appears that part of the problem is not that
the ready function fires again (though that is possible aparently),
but that changing the DOM causes the script that creates the ready
function to fire again, adding an additional ready function, etc etc.
This seems to happen if the javascript is embedded in the html at a
point beyond (or contained in) the part of the DOM that the ready
handler modifies. (Obviously would be better to put script that
creates a ready function in the document head, but in this case that's
not an option.) Problem fixed by checking a global flag variable to be
undefined before executing jQuery(document).ready(...).
If this might be your problem, you can adopt the same solution:
var onLoadFired = false;
$(document).ready(function() {
/* Ensure this function only runs once */
if (onLoadFired) {
return;
}
else {
onLoadFired = true;
}
/* Business logic */
// .. your code here ..
});
Or, better, move your handler into a separate script file that's included by a script tag in your page's head element.
Try this:
$(window).bind("load", function() {
...
});

How to call JavaScript function from body of HTML document on pageload-complete

I have some JavaScript (code to initialize Google Maps if you're interested) that I'm forced to include within the <body></body> tags of an html document and I would like to have one of my methods trigger on page-load complete. The catch is that I don't have access to the <body> html tag, so I can't do:
<body onload="foo()">
Is there any way to accomplish this? I realize this is a ridiculous scenario.
Depending on when the code is run, attach the handler with JavaScript:
if(window.onload) {
var _existing = window.onload;
window.onload = function() {
_existing();
foo();
};
}
else {
window.onload = foo;
}
As you seem to have no control over the page we have to be a bit more careful. Other JavaScript might already have set an event handler. To be a good citizen, we don't just overwrite the event handler, but keep a reference to it in case it exists.
However other JavaScript code could overwrite this again.
The best way would be to use the more advanced event handling methods addEventListener (W3C) and attachEvent (IE).
For more information about event handling I suggest to read the excellent articles on quirksmode.org.
If you are using jQuery you can use $(document).ready:
$(document).ready(function() {
// put all your jQuery goodness in here.
});
See this tutorial.
window.onload = foo;
function foo(){
alert("page loaded!");
}
You can programattically attach events using the DOM.
// Function to add event listener to body
function addLoadFn()
{
var body = document.getElementById("body");
body.addEventListener("load", myOnloadListener, false);
}

Mozilla Closure Example

JS BIN Attempt
Attempting to follow along with the example, but it doesn't seem to work. A little confused, as it is Mozilla.
Mozilla
As #Xaerxess mentions, you need to call the "setupButtons" function when the DOM is ready for manipulation; typically one does that by adding an event handler to the window "load" event, which happens when the page is entirely loaded (which is what the jQuery idiom $(document).ready(function(){...}); does.
Try adding this snippet to the end of your existing <script> element to accomplish that goal using plain JavaScript, no jQuery needed:
window.onload = function() { setupButtons(); };
Another typical way of doing this is to use the element.addEventListener function; the difference is that you can add multiple event callbacks this way and they won't overwrite each other:
window.addEventListener('load', function() {
setupButtons();
}, false);
You didn't call setupButtons function on page load, only defined it. If you include jQuery, add:
$(document).ready(setupButtons);
in you script tag and it'll work.

How can I notify the parent page when a popup has finished a load which the parent initated?

My main HTML page does the following:
var popup = window.open(...);
// Wait for popup to load
popup.onload = function() { do_something(); };
popup.location = "new-page.html";
I'd like do_something to be called when new-page.html is finished loading. But what I currently have doesn't work -- do_something is never called.
How can I make this work?
I only care about getting this to work in Firefox 3.5, if that makes things easier.
you could use window.opener.<functionName> and put your notification code within that function on the parent page
Have you tried using the opener object?
http://www.webreference.com/js/tutorial1/opener.html
Or, without messing with the HTML of the child window, from the parent, you can attach a listener on the load event of the iframe. In this solution, i am going to use jQuery for simplicty, but any library or even manual event attachment will do.
In the parent's HTML:
<iframe id="foo"></iframe>
<script type='text/javascript'>
var element = $("#foo");
element.load( function( eventObject ) {
// do something here
} );
// Now that the event listener is attached, we can set the source.
element[0].src = "foo.html";
</script>
Note, I have not tried setting the source first and then attaching the listener, I am not sure if this would be guaranteed to always work. It could happen that the iframe is created/loaded before the load listener is attached, I am not sure. But, by setting the src after the listener is attached, I am sure that the load listener will be called.
Shane
http://www.shanetomlinson.com
http://www.ubernote.com
Try having the doSomething method called in the popup's onload. You can refer back to the parent by using window.opener
In your .html that is loaded you could have a simple one liner at the end that calls a function on the opening window (if it exists)
<script type='text/javascript'>
if (window.opener && window.opener.do_something) window.opener.do_something(window);
</script>

Categories