External javascript window.onload firing early - javascript

I have a page that references an external javascript file, and when I tell it run a function onload, it is giving me errors (I assume because it is firing before the page is loaded.) "Cannot set property 'innerHTML' of null"
What do I need to do here to fire run() after the page is loaded?
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="js/test.js"></script>
</head>
<body>
<div id="test"></div>
</body>
</html>
JS
window.onload = run();
function run() {
document.getElementById("test").innerHTML = "found it";
}

It should be:
window.onload = run;
When you do:
window.onload = run();
You're actually running the function called run, and then assigning its return-value (undefined in this case) to window.onload.
This function is running before the page even gets loaded (since you are running it explictly by doing run()), at which time the div with id test doesn't even exist. This is why you're getting the error.

Try this instead:
window.onload = run
When you do window.onload = run() you are immediately executing run() and assign whatever is returned to the window.onload property. This is why it’s not working correctly.

Related

Global method not being called unless I have a window.setTimeout of 1000 ms around the call

I have an index.html file and in it I have a script tag that's receiving a callback from google maps. If I remove the timeout, I get this error.
Uncaught TypeError TypeError: window.globalMethod is not a function
My 'globalMethod' is located in a directive being used on the page and I would assume maybe the directive's constructor isn't loaded, but I'm running the google maps script after <app-root></app-root> so you would think it would find window.globalMethod()?
I tried it with 100, but that doesn't seem to be long enough and still receive the error.
Here is index.html
<!doctype html>
<html lang="en">
<head>
// left out other head tags for brevity
<script>
function initPlaces() {
// won't run if I remove window.setTimeout
window.setTimeout(() => {
window.globalMethod();
}, 1000);
}
</script>
</head>
<body>
<app-root></app-root>
<script src="https://maps.googleapis.com/maps/api/js?key=secret-key&libraries=places&callback=initPlaces" type="text/javascript"></script>
</body>
</html>

JavaScript addEventListener makes function run directly

My Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ATM Interfacetest</title>
<link rel="stylesheet" type="text/css" href="css/rahmen/rahmen.css">
<script>
function testwindow(){
var tmp = document.createElement('div');
tmp.id = 'idtest';
tmp.className = 'classtest';
document.getElementById('xbuttonsHeinz-Ulf').appendChild(tmp);
document.getElementById('idtest').addEventListener('click', test(), false);
}
function test(){
alert('Alarm!');
}
</script>
</head>
<body onload="testwindow()">
<div id="xbuttonsHeinz-Ulf" class="xbuttons">
<div id="schließenHeinz-Ulf" class="symbol">x</div>
<div id="minimierenHeinz-Ulf" class="symbol"> - </div>
<div id="maximierenHeinz-Ulf" class="symbol">□</div>
</div>
</body>
</html>
Drives me crazy. Trying to add the Eventlistener makes the test() function to be excuted directly, without waiting to clicked.
Whats my mistake.
I searching for a good idea to dynamically create html tags with option to add eventhandlers.
Trying:
tmp.onclick = test();
also executes the function directly w/o waiting for a click.
Given the expressions
test() - the result of a call to the function test with no
arguments passed.
test - a reference to the function test.
You want the latter. The former calls test as soon as the line is reached. addEventListener(...) wants a reference to an EventListener, not the result of the handled event.

document.onload() strange behaviour, few questions?

Before you start reading, don't vote me down, its not just another question about window.onload vs document.onload.
window.onload should trigger once all DOM nodes are fully loaded.
document.onload should trigger once all DOM nodes are ready, it won't wait for all the assets to fully load.
Now if we have something like this with window.onload:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
window.onload = function() {
alert('Loaded!');
};
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
The script will wait until image is fully loaded and then trigger alert.
And if we have something like this with document.onload:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
document.onload = function() {
alert('Loaded!');
};
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
Nothing will happen and script won't load at all, unless we make our function self executing like this:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
document.onload = function() {
alert('Loaded!');
}();
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
And now the script will work but won't wait for image to fully load like it does with window.onload.
Now I have 2 questions really:
Why do we need to create self executing functions with document.onload, and window.onload works without making our function self executing? It works the same in latest versions of Chrome and Firefox so I guess its how it its suppose to work, but why?
What is really happening there with that code once we assign document.onload a function? I understand that its a way to wait for DOM to load. But we are saying that window.onload = function() { } Should this make a window a function? Or is that window has eventListener attach to it, that is triggered by onload trigger? Looks like answered this question myself... :) Is it true?
Thanks!
document.onload should trigger once all DOM nodes are ready, it won't wait for all the assets to fully load.
You are operating under a misapprehension. That is not the case.
Why do we need to create self executing functions with document.onload
Because there is no such thing as document.onload. It is an arbitrary property name with no special meaning.
If you assign a function to it, nothing will happen other than that its value will be the function.
If you immediately invoke the function and assign the return value, then the function will be invoked (immediately, before the DOM is ready) and nothing special will happen to the value you store on the property.
If you want to run a function when the DOM is ready then use the DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});

Attaching onclick event to element is not working

I just started learning Javascript, and I know next to nothing. I am trying to attached an onclick event to an element in my HTML.
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
This is my code so far. Nothing happens when the element with the ID of header is clicked on. What am I doing wrong?
the following is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
<script src="testing.js"></script>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
</body>
</html>
The issue is, that you try to load a html element, which does not "exists" when the javascript function is executed, because the dom has not finished loading.
To make your code work, you can try following solutions:
Place your script tag below in the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Testing Page</title>
</head>
<body>
<h1 id="header">Andrew Dawson</h1>
<script src="testing.js"></script>
</body>
</html>
Add an event handler to check if the window element is ready:
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded(){
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
}
Another solution would be to use jquery framework and the related document ready function
http://api.jquery.com/ready/
I think the solve you are looking for is
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").setAttribute("onclick", joinList);
Your code seems straight forward, maybe your script is running before the DOM fully loads. To keep it simple across all browsers we can place a self executing anonymous function at the end to initiate all your scripts after DOM loads.
<html>
<title></title>
<head></head>
<body>
html here!!
<script>
(function() {
//Any other scripts here
var joinList = function() {
alert("This should display when clicked");
}
document.getElementById("header").onclick = joinList;
})();
</script>
</body>
</html>
The above is purely javascript, not to be confused with the shorthand (see below) of the jquery "document onready" function (you would need to add jquery to your pages).
$(function() {
//your javascript code here
});
Why using self executing function?

Result of getElementById is null?

Just struggling with a Javascript class being used as a method for some cometishian code, how do I have a constructor for this code? The following code is invalid:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="Stylesheet" href="gStyle.css" />
<script type="text/javascript" language="javascript">
// Gantt chart object
function ganttChart(gContainerID) {
this.isDebugMode = true;
this.gContainer = document.getElementById(gContainerID);
if (this.isDebugMode) {
this.gContainer.innerHTML += "<div id=\"gDebug\">5,5 | 5.1</div>";
}
}
var myChart = new ganttChart("chart1");
</script>
</head>
</html>
<body>
<div id="chart1" class="gContainer"></div>
</body>
</html>
this.gContainer is null
That is because you are running the script before the page is ready, i.e. chart1 doesn't exist yet when you call new ganttChart("chart1");. Wrap the code inside window.onload = function() { } or run it at the bottom of the page.
The problem is that your script is running too early, it's looking for an element that doesn't exist in the DOM yet, either run your script onload, or place it at the end of the <body> so your id="chart1" element is there to be found when it runs.
Problem is that you run your code before the page has loaded yet, and thus the DOM element with id chart1 does not exist at the moment the code is executed.
use
window.onload = function(){myChart = new ganttChart("chart1");};
Note that using window.onload like that will override all previously stated window.onload declarations. Something along the following lines would be better:
<script type="text/javascript">
var prevOnload = window.onload || function () {};
window.onload = function () {
prevOnload();
// do your stuff here
};
</script>
Also, untill al images are fully loaded onload will not trigger, consider using jquery & $(document).ready or similar.
:)
Regards,
Pedro

Categories