window.addEventListener in a conditional - javascript

I'm running into an odd problem where window.addEventListener (or window.attachEvent) doesn't seem to be firing when called from within an if/else block. For example, say I have the following html and javascript files:
test.html
<!DOCTYPE html>
<html>
<head>
<META HTTP-EQUIV="cache-control" CONTENT="no-store">
<script type="text/javascript" src="test.js"></script>
<script type="text/javascript">
var tst = new Tester();
if (window.addEventListener) {
window.addEventListener("load", tst.onloadFunc, false);
console.log("addEventListener in conditional");
} else if (window.attachEvent) {
window.attachEvent(window.attachEvent("onload", tst.onloadFunc));
console.log("addEvent in conditional");
}
//window.addEventListener("load", tst.onLoadFunc, false);
</script>
</head>
<body>
</body>
</html>
test.js
function Tester() {
this.onLoadFunc = function() {
console.log("in Tester");
}
}
If I visit test.html and fire up a javascript inspector, I see "addEventListener in conditional" logged. However, I do not see "in Tester" logged.
Now, if I uncomment the addEventListener line outside of the if/else, I do see "in Tester" logged.
Can someone explain why this is happening? Is there any way around it or a better way of accomplishing the same thing?

Javascript is case-sensitive.
You should pass tst.onLoadFunc instead of tst.onloadFunc as an argument to addEventListener.

Your capitalization of onLoadFunc is wrong in the conditional window.addEventListener call.

Related

Load event isn't working in Google chrome

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

onunload on body is not working

I tried my code on chrome, opera, firefox and edge but it's not working. My onload code works perfectly, but onunload doesn't work on all. Do not know why?
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body onload="loaded()" onunload="unloaded()">
<script type="text/javascript">
function loaded(){
alert("The page loaded!");
}
function unloaded(){
alert("Come again!");
}
</script>
</body>
</html>
Some operations are not allowed on onunload event showing alert is one of them. Check this answer.
You can use below code to display a warning message to users.
window.onbeforeunload = function(e) {
return 'Bye now!';
};
when you invoke the unload function,the DOM is completely unload now.
So there can't show an alert window for you.
But you can see the log printed in the console if you use
---> console.info("Come again!");

addEventListener not working on any browser

I ran the below code and tried it on all browsers but it didn't work
//HTML Code
<html>
<head><title>Test</title></head>
<body onload="LaunchImageSlider();">
<script type="text/javascript" src="Scripts/javascript code.js"></script>
</body>
</html>
//javascript code.js
function LaunchImageSlider() {
window.addEventListener("load",function() {alert("Hi")});
}
I did not get any alert message. My actual aim is to create an image slider once the page is loaded so I began first by seeing whether the "addEventListener" works.
What am I doing wrong here?
I referred to the below questions already, but nothing helped:
addEventListener is not working
addEventListener() not working
addEventListener not working
addEventListener in javascript
A possible solution:
<html>
<head>
<title>Test</title></head>
<body>
<script type="text/javascript" src="Scripts/javascript code.js"></script>
<script type="text/javascript">
(function () {
LaunchImageSlider();
})();
</script>
</body>
</html>
But in the function you should not add and eventListener, as it is run after the window has loaded. You should just run the callback method directly. So using your example:
//javascript code.js
function LaunchImageSlider() {
alert("Hi");
}

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?

Why isn't the javascript onclick function called?

I have created a JSFiddle to describe the issue. Why isn't the alert displayed when I call the doSomething() function?
You need to disable framework option in jsfiddle for javascript to work
DEMO
function doSomething() {
alert('Hello!');
}
This is because doSomething() function is not defined in the HTML page. In jsfiddle your function (in js pane) is wrapped by document onload event of jquery. (see at the left side of jsfiddle for settings). So Its executed like this,
$(document).ready(function() {
function doSomething() {
alert('Hello!');
}
});
See how its wrapped. Its not accessible. To fix it you should assign it to window object.
In the js pane write the function as
window.doSomething=function() {
alert('Hello!');
}
It'll work
Its recommended you do not use onclick attributes of an HTML elements. Its better to assign event handler with JS.
$("img").click(function(){
alert("Hello");
});
This is a "fiddle-thing". Pick nowrap (head) from the first selection in the "Choose Framework" field.
What JsFiddle does for you is creating the <HTML>, <head> and <body> tags for you. You shouldn't include them in your HTML, because that would make the markup invalid after JsFiddle processed it. It also wraps your JS in the document's onload event. So your function was not defined in the root scope as you thought, but in th scope of the document.onload function, and you couldn't reach it from within the body, because that is outside of that function. I changed the JsFiddle attribute 'wrap in' to 'no wrap (head)' and it worked.
Your function dosomeThing() is not defined in the page
just replace header tag with this one
<head>
<script>
function doSomething() {
alert('Hello!');
}
</script>
</head>
and then try again
Here is your complete code. just copy and paste your editor. it is
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<title>Javascript Events</title>
<script type='text/javascript'>
window.onload = function() {
var image_one = document.getElementById('imageOne');
var image_two = document.getElementById('imageTwo');
image_one.onclick = function() {
alert('Hello!');
}
image_two.onclick = function() {
alert('Hello!');
}
}
</script>
</head>
<body>
<img id="imageOne" src="http://upload.wikimedia.org/wikipedia/commons/thumb/0/0c/White_and_yellow_flower.JPG/320px-White_and_yellow_flower.JPG" />
<img id="imageTwo" src="http://upload.wikimedia.org/wikipedia/en/7/70/Example.png" />
</body>
</html>

Categories