Load event isn't working in Google chrome - javascript

So I'm just learning about load event handler and when I run the code in Google chrome it doesn't work can someone tell me why and how I can fix
it. By the way as u can see I want the alert function to execute as soon as everything is loaded thanks
This is my code below 👇
<!DOCTYPE HTML>
<html>
<head>
<title>Button</title>
<meta charset="utf-8">
<style>
body{
display:grid;
height:100vh;
}
h2{
margin:auto;
}
</style>
</head>
<body>
<h2>experiment</h2>
<script>
var exp =document.querySelector("h2");
function fun(){
alert("is it a success?");
}
exp.addEventListener("load", fun);
</script>
</body>
</html>

Use DOMContentLoaded instead
The DOMContentLoaded event will trigger earlier and is usually
considered the better option.
document.addEventListener('DOMContentLoaded', fun);
[the load event] should be used only to detect a fully-loaded page. It
is a common mistake to use load where DOMContentLoaded would be more
appropriate.
If you must use the load event
If you must use the load event, you can add a listener to window instead:
window.addEventListener('load', fun);

Related

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");
});

what's the difference between onload action and an action in a bottom script

Is there any functional difference between using body onload:
<!DOCTYPE html>
<html>
<head>
<title>testing body onload</title>
</head>
<body onload="fu('this is from body onload')">
<h2 id="I1">nothing yet</h2>
<script>
function fu (msg) {
document.getElementById("I1").innerHTML = msg ;
}
</script>
</body>
</html>
on the one hand and executing a script at the end of the body:
<!DOCTYPE html>
<html>
<head>
<title>testing body onload</title>
</head>
<body>
<h2 id="I1">nothing yet</h2>
<script>
function fu (msg){
document.getElementById("I1").innerHTML = msg ;
}
fu('this is from bottom script') ;
</script>
</body>
</html>
The second seems better to me, certainly when there are more actions to do when a page is loaded. But maybe there is a pitfall I don't know?
Yes, there is. Putting your code at the bottom is like putting it in a domready event, not onload.
Domready means that the html code was read (so the dom is ready, or in other words, you can now find dom elements with js selectors), while onload means that all the assets (img, css, etc..) are loaded as well (so, a much longer event).
Edit:
please also refer to MDN docs:
(this is basically like jquery's domready, and it's a document object's event):
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
this is the onload event, and it's a window object's event:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
onload documentation from Mozilla:
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images, scripts, links and sub-frames have finished loading.
Placing scripts at the base of the page will run as soon as the browser has rendered the HTML.
For perception purposes I would combine the two and place your scripts at the bottom of the page in an onload callback, if needed.

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?

appMobi onClick does not work

I am really new to appMobi, HTML and JavaScript. The only thing I want to do is that I have a button with an onClick method and this method should do anything.
I have defined a Script, I have a button but the method doesn't get called. Can someone please tell my why? The examples provided by appMobi don't do anything different - I think.
Here is my code:
<head>
<!-- the line below is required for access to the appMobi JS library -->
<script type="text/javascript" charset="utf-8" src="http://localhost:58888/_appMobi/appmobi.js"></script>
<script type="text/javascript" language="javascript">
// This event handler is fired once the AppMobi libraries are ready
function onDeviceReady() {
//use AppMobi viewport to handle device resolution differences if you want
//AppMobi.display.useViewport(768,1024);
//hide splash screen now that our app is ready to run
AppMobi.device.hideSplashScreen();
}
//initial event handler to detect when appMobi is ready to roll
document.addEventListener("appMobi.device.ready",onDeviceReady,false);
function myfunction(){
AppMobi.debug.log("test");
alert("Hallo Welt");
}
</script>
<script type="text/javascript">
function myfunction(){
AppMobi.debug.log("test");
alert("Hallo Welt");
}
</script>
</head>
<body >
<br>
<button onclick="myfunction();">MyButton</button>
</body>
Finally, I found the solution!
Instead of onclick="myfunction" you have to use ontouchstart="myfunction"!
Would be nice if someone could tell me why.

JavaScript: trouble assigning event handlers

I'm not sure what I'm doing wrong here:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
eventInit.js
window.onload = function () {
alert("check"); // works
var jsWarning = document.getElementById("javascriptWarning");
jsWarning.onclick = function () {
alert("hi"); // works
};
jsWarning.onload = function () {
alert("loaded"); // fails
};
}
And yet, nothing happens. What am I doing wrong? I've tried other events, like onmouseover and onload.
I'm doing this in Visual Studio, and intellisense isn't giving me options for setting any event handlers. Is that because I'm doing this wrong?
I have confirmed that JS is working on my setup; just putting alert("hi") in a script and including it does work.
It might be important to note that I'm doing this in JScript, since I'm using Visual Studio 2010, so perhaps event handling is different?
Updated to remove '-' from the ID name, but it still doesn't work.
Updated added the window.onload block. Now onclick works, but onload doesn't.
You are trying to set a load event on a paragraph. Only objects which load external data (window, frame, iframe, img, script, etc) have a load event.
Some JS libraries implement an available event (such as YUI) — but you know the paragraph is available, since you're setting an event on it, and you couldn't do that if it was unavailable.
maybe you forgot to have the code block inside a
window.onload = function() {
// btn click code here
}
You have to wait for the document to be parsed before you can go looking for elements by "id" value. Put your event handling setup into an "onload" function on the window object.
The browser won't fire an "onload" event on your <p> tag. You won't need that anyway if you do your work in the "onload" handler for the window as a whole.
[soapbox] Use a framework.
The script is executed before the desired element exists. Additionally, I don't think, p has an onload-Event. Windows, frames and images, yes, but paragraphs?
You should use <body onload="init();"> or window.onload=function(){ … } or a library function, if you use a library. Example:
index.html
<?xml version="1.0" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "XHTML1-s.dtd" >
<html xmlns="http://www.w3.org/TR/1999/REC-html-in-xml" xml:lang="en" lang="en" >
<head>
<script type="text/javascript" src="scripts/eventInit.js"></script>
</head>
<body>
<p id="javascriptWarning">This page will not work with JavaScript disabled.</p>
</body>
</html>
scripts/eventInit.js
window.onload=function(){
alert('JS is working!');}
Edit: Okay, I am very sure, p makes no use of an onload event handler. And it's no wonder, you don't need it. If you want to execute JS code just after the paragraph is finished, do this:
<p>
<!-- stuff -->
</p>
<script type="text/javascript">
/* stuff */
</script>
Instead of this:
jsWarning.onload = function () {
alert("loaded"); // fails
};
try this
if(jsWarning) alert("loaded");
I think someone above mentioned checking for the existence of the element. At this stage the element should be present but it does no harms to check for it.
I think you have to make sure your JavaScript is binding.
Is your javascript before or after your paragraph element, for some reason my brain is aiming towards that.
I would look into using something like jQuery, it will help.
using jQuery your code would be (with the relevant jQuery files included of course):
$(document).ready(function()
{
$("#javascript-warning").click(function(){
alert("HELLO");
});
});
I don't think hyphens are valid in class names when used in conjunction with JavaScript. Try an underscore instead.
onload is a window event.

Categories