JavaScript event window.onload not triggered - javascript

I've got the following code in a website:
window.onload = resize;
window.onresize = resize;
function resize(){
heightWithoutHeader = (window.innerHeight - 85) + "px";
document.getElementById("main-table").style.height = heightWithoutHeader;
document.getElementById("navigation").style.height = heightWithoutHeader;
}
The onresize works fine, but the onload event never fires. I've tried it in Firefox and Chrome and neither of them works.
Thank you for your help and go for the reputation! ;D

I think what's probably happening here is that your window.onload is being overridden later, check to make sure that it's not via things like <body onload="">
You can check this by alert(window.onload) in your re-size function, to see what's actually attached there.

I had this happen when I added 3rd party jQuery code we needed for a partner. I could have easily converted my antiquated window.onload to a jQuery document ready. That said, I wanted to know if there is a modern day, cross browser compatible solution.
There IS!
window.addEventListener ?
window.addEventListener("load",yourFunction,false) :
window.attachEvent && window.attachEvent("onload",yourFunction);
Now that I know ... I can convert my code to use the jQuery route. And, I will ask our partner to refactor their code so they stop affecting sites.
Source where I found the fix --> http://ckon.wordpress.com/2008/07/25/stop-using-windowonload-in-javascript/

Move the window.onload line to the end of the javascript file or after the initial function and it will work:
function resize(){
heightWithoutHeader = (window.innerHeight - 85) + "px";
document.getElementById("main-table").style.height = heightWithoutHeader;
document.getElementById("navigation").style.height = heightWithoutHeader;
}
// ...
// at the end of the file...
window.onload = resize;
window.onresize = resize;
But it's a best practice if you don't replace the onload too. Instead attach your function to the onload event:
function resize(){
heightWithoutHeader = (window.innerHeight - 85) + "px";
document.getElementById("main-table").style.height = heightWithoutHeader;
document.getElementById("navigation").style.height = heightWithoutHeader;
}
// ...
// at the end of the file...
window.addEventListener ?
window.addEventListener("load",resize,false)
:
window.attachEvent && window.attachEvent("onload",resize);
That worked for me and sorry for my english.

This answer is for those who came here because their window.onload does not trigger.
I have found that for the following to work
window.onload = myInitFunction;
or
window.addEventListener("load", myInitFunction);
the referred function (myInitFunction in this case) must reside (or be defined) within the same <script>-element or in a <script>-element that occurs before the <script>-element where the onload event is established. Otherwise it will not work.
So, this will not work:
<html>
<head>
<title>onload test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
window.addEventListener("load", myInitFunction)
</script>
<script>
function myInitFunction() {
alert('myInitFunction');
}
</script>
</head>
<body>
onload test
</body>
</html>
But this will work:
<html>
<head>
<title>onload test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function myInitFunction() {
alert('myInitFunction');
}
</script>
<script>
window.addEventListener("load", myInitFunction)
</script>
</head>
<body>
onload test
</body>
</html>
And this will work (since we only have one <script>-element):
<html>
<head>
<title>onload test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
window.addEventListener("load", myInitFunction)
function myInitFunction() {
alert('myInitFunction');
}
</script>
</head>
<body>
onload test
</body>
</html>
If you for some reason have two <script>-elements and cannot (or do not want to) merge them and you want the onload to be defined high up (i.e. in the first element), then you can solve it by
instead of writing
window.onload = myInitFunction;
you write
window.onload = function() { myInitFunction() };
or, instead of writing
window.addEventListener("load", myInitFunction);
you write
window.addEventListener("load", function() { myInitFunction() });
Another way to solve it is to use the old
<body onload="myInitFunction()">

For me, window.onload was not working when wrote inside script type="text/javascript tag.
Instead, needed to write the same in script language="Javascript" type="text/javascript tag and it worked fine.

In my case
window.addEventListener("load", function() {
myDropdownFunction();
});
surprisingly (for me) didn't help (I tried to set a value for dropdown when user uses browser backwards button). And window.onload didn't work for the reason Nick Craver♦ explained here above - it was overridden by <body onload="...">.
So I tried this using jQuery and it worked like a charm:
$(window).on('pageshow', function() {
alert("I'm happy");
});

This works for me, i think your problem is somewhere else:
function resize(){
var tester = document.getElementById("tester"),
html = tester.innerHTML
tester.innerHTML = html + "resize <br />"
}
window.onload = resize;
window.onresize = resize;
you can test it yourself here:
http://jsfiddle.net/Dzpeg/2/
are you sure its the only event called onLoad ? Maybe an other onLoad event creates a conflict

put "_blank" as the target param has solved in my case
let wind = open(url,"_blank","options here")
wind.onload = .... // works fine now

Just in case someone finds it useful, I was calling twice the function, instead of once:
window.onload = function() {...}

In my case the problem was that my script was being loaded dynamically by another one (e.g.: with $.getScript()) and when it ran the window 'load' event had already fired.
My solution:
if (
document.readyState === "complete" ||
document.readyState === "interactive"
) {
// load event already fired, this may happen if this script is loaded dynamically.
// Run immediately.
execOnLoad();
} else {
// SEE: https://stackoverflow.com/questions/2810825/javascript-event-window-onload-not-triggered
window.addEventListener
? window.addEventListener("load", execOnLoad, false)
: window.attachEvent && window.attachEvent("onload", execOnLoad);
}

This will be work when you call the "window.onload" next to the function resize()

If it's really in that order, it's definitely not going to work. You can't assign a function to an event handler before the function itself is declared.

Related

afterprint not detected while hidden printing in an iFrame

I've spent nearly 2 days googling and trying lots of example (even here in StackOverflow), and I don't find any way to fire the event "afterprint". It seems dead. I've found some fiddle, where it works, and when I try to reproduce on my system, it doesn't.
I am not sure what I'm doing wrong.
Here is the code I want to use:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PDF Printing</title>
</head>
<body>
<button id="myButton2" onClick="printPage('http://localhost/~user/testPDF.pdf')">Print Me 2</button><br>
<script type="text/javascript">
function closePrint () {
console.log("Ciao");
document.body.removeChild(this.__container__);
}
function printPage (sURL) {
var myButton = document.getElementById("myButton2");
myButton.disabled=true;
var printFrame = document.createElement("iframe");
printFrame.id = "printPDF2";
printFrame.style.display = 'none';
printFrame.src = sURL;
printFrame.onload = function() {
printFrame.contentWindow.addEventListener('afterprint', function(evt) {
console.log("yellow");
document.body.removeChild(iframe)
});
this.contentWindow.__container__ = this;
this.contentWindow.onbeforeunload = closePrint;
this.contentWindow.onafterprint = closePrint;
this.contentWindow.focus(); // Required for IE
this.contentWindow.print();
}
document.body.appendChild(printFrame);
}
</script>
</body>
</html>
I've tried also with the MediaDetect. And it doesn't work... (I used these links for inspiration: https://jsfiddle.net/5qbc1pzj/ and https://jsfiddle.net/anhhnt/nj851e52/) the JS console is empty... I get no "Ciao" or "yellow"...
I'm using a simple Apache server, and using the latest IE Edge (103.0.1264.62).
I am out of idea, could someone give me an idea, where to look at?
Thank you in advance.
Kind regards,
Alessandro
It doesn't work because detecting the print events only work for HTML-documents. The MIME type for PDF windows is application/pdf so it doesn't work. The events that are available on the window are not available to the <embed> like tags, as they are handled by the browser's default application for the type. Although the event occurs here, it is not bubbled back to the window. For more information, you can refer to this answer.
The only solution to this seems to create your own PDF viewer. For example, you can use PDF.js.

Execute javascript on whole dom is loaded [duplicate]

I'm working without the JavaScript framework, but I want to call a function just when the DOM is loaded.
I can't/don't want to use the attribute onload on the <body> tag.
I think http://code.google.com/p/domready/ is exactly what you're looking for.
If you are ever writing your own JavaScript file that cannot depend on
the existing libraries out there and would like to execute only after
the page is loaded, this library is for you.
Simply do this:
<html lang="en">
<head>
<script src="domready.js" type="application/javascript"></script>
<script type="application/javascript">
DomReady.ready(function() {
alert('dom is ready');
});
</script>
</head>
<body>
</body>
</html>
Here is the code:
in non-IE browsers, use DOMContentLoaded event
in IE top frame use scroll hack (see _readyIEtop)
in IE frame, simply use onload
var onready = function(handler) {
// window is loaded already - just run the handler
if(document && document.readyState==="complete") return handler();
// non-IE: DOMContentLoaded event
if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
// IE top frame: use scroll hack
else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
// IE frame: use onload
else if(window.attachEvent) window.attachEvent("onload",handler);
};
// IE stuff
var _readyQueue = [];
var _readyIEtop = function() {
try {
document.documentElement.doScroll("left");
var fn; while((fn=_readyQueue.shift())!=undefined) fn();
}
catch(err) { setTimeout(_readyIEtop,50); }
};
jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.
var test = function() { alert("ok"); }
onready(test);
Well, I'm afraid cross-browser and DOM loaded don't go together easily. By recommendation is Ryan Morr's ondomready (https://github.com/ryanmorr/ondomready) but there are a ton of alterntives.

Dom loaded event cross borwser native javascript code

I'm working without the JavaScript framework, but I want to call a function just when the DOM is loaded.
I can't/don't want to use the attribute onload on the <body> tag.
I think http://code.google.com/p/domready/ is exactly what you're looking for.
If you are ever writing your own JavaScript file that cannot depend on
the existing libraries out there and would like to execute only after
the page is loaded, this library is for you.
Simply do this:
<html lang="en">
<head>
<script src="domready.js" type="application/javascript"></script>
<script type="application/javascript">
DomReady.ready(function() {
alert('dom is ready');
});
</script>
</head>
<body>
</body>
</html>
Here is the code:
in non-IE browsers, use DOMContentLoaded event
in IE top frame use scroll hack (see _readyIEtop)
in IE frame, simply use onload
var onready = function(handler) {
// window is loaded already - just run the handler
if(document && document.readyState==="complete") return handler();
// non-IE: DOMContentLoaded event
if(window.addEventListener) window.addEventListener("DOMContentLoaded",handler,false);
// IE top frame: use scroll hack
else if(window.attachEvent && window==window.top) { if(_readyQueue.push(handler)==1) _readyIEtop(); }
// IE frame: use onload
else if(window.attachEvent) window.attachEvent("onload",handler);
};
// IE stuff
var _readyQueue = [];
var _readyIEtop = function() {
try {
document.documentElement.doScroll("left");
var fn; while((fn=_readyQueue.shift())!=undefined) fn();
}
catch(err) { setTimeout(_readyIEtop,50); }
};
jQuery tunes the IE a little more (lots of code), but in my tests it runs just before onload event anyway.
var test = function() { alert("ok"); }
onready(test);
Well, I'm afraid cross-browser and DOM loaded don't go together easily. By recommendation is Ryan Morr's ondomready (https://github.com/ryanmorr/ondomready) but there are a ton of alterntives.

Why does window.onload work while document.onload doesn't?

Can anyone tell me why the following page doesn't trigger an alert when it loads? If I use window.onload instead of document.onload it works. Why is there this difference?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
document.onload = function() {
alert('Test');
}
</script>
</head>
<body>
</body>
</html>
The simplest answer is that it just wasn't designed that way. The browser executes the function attached to window.onload at the "end of the document loading process". It does not attempt to execute a function attached to document.onload.
You could assign a function to document.onload but the browser will not do anything special with it.
Some things to keep in mind (assuming you've just assigned a function to one or the other of window.onload or document.onload):
window.onload === onload
window.onload !== document.onload
window !== document
The event handler is onload not document.onload. It hangs directly off the window object (which is the default object).

why the following code works in safari but not in IE6?

why the following code works in safari but not in IE6 ? It opens the window but doesnt trigger the alert.
<script>
function fnOpenChild()
{
var openChild = window.open('child.htm');
openChild.onload = function() {
alert("im the child window");
};
}
</script>
<input type="button" onClick="fnOpenChild()">
Thank You
try it!
to move onload event to child.htm
I know this isn't actually an answer, but I really suggest you don't use IE6 anymore, and just go with IE8+.
Afterwards, add code that will warn the user that he/she is using an out-dated web browser. You can detect the browser version using navigator.appVersion
If you want to know why you or anyone else shouldn't use it anymore:
http://www.google.nl/#hl=nl&source=hp&biw=1024&bih=837&q=Why+IE6+must+die
Edit: Aah, I guess you fixed it, but I still suggest you take a look at the link above. :)
IE6 has some... rather interesting issues and it requires some workarounds. Have you tried googleing, "IE6 window onload"? http://www.webdeveloper.com/forum/showthread.php?t=183578 seems to have a working suggestion.
Try applying onreadystatechange as well. IE6 has some issue with onload.
openChild.onload = openChild.onreadystatechange = function() { ...
There could be two possible work-arounds:
1. Move the onload script ot the childwindow
**child.htm**
<html>
<script type="text/javascript">
window.onload = function(){
alert('im the child window');
}
</script>
<body>
....
</body>
</html>
2. Declare a function in the opener window and call it on the the child's onload
**parent.htm**
<script type="text/javascript">
function forChildWindow(params){
alert('im the child window' + params);
}
</script>
**child.htm**
<html>
<script type="text/javascript">
window.onload = function(){
var load = window.opener.forChildWindow;
var someparams = " param1";
if(load) {
load(someparams);
}
}
</script>
<body>
....
</body>
</html>

Categories

Resources