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.