Javascript, running on strict mode, does nothing if you use an id's value as variable, even without declaring it. Here is an example (see how linkhome and linkshop are not declared):`
'use strict';
var gameWorld = {
contentoutput: document.getElementById("contentoutput"),
linkupgrade: document.getElementById("linkupgrade"),
linkachievement: document.getElementById("linkachievement"),
addEventHandlers: function() {
linkhome.addEventListener("click", function() {
loadContent("contenthome")
});
linkshop.addEventListener("click", function() {
loadContent("contentshop")
});
linkupgrade.addEventListener("click", function() {
loadContent("contentupgrade")
});
linkachievement.addEventListener("click", function() {
loadContent("contentachievement")
});
linkajaxhome.addEventListener("click", loadHtml);
}
}
function loadContent(contentid) {
var x = document.getElementById(contentid).innerHTML;
contentoutput.innerHTML = x;
}
function init() {
gameWorld.addEventHandlers();
}
document.addEventListener("DOMContentLoaded", init);
.hidden {
display: none
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<nav>
<ul>
<li><a href="#" id="linkhome">Home</a>
</li>
<li><a href="#" id="linkshop">Shop</a>
</li>
<li><a href="#" id="linkupgrade">Upgrade</a>
</li>
<li><a href="#" id="linkachievement">Achievement</a>
</li>
</ul>
</nav>
<section id="contentoutput">
</section>
<div class="hidden">
<div id="contenthome">
<h1>Home Page</h1>
<p>This is the text of the home page</p>
</div>
<div id="contentshop">
<h1>Shop Page</h1>
<p>This is the text of the shop page</p>
</div>
<div id="contentupgrade">
<h1>Upgrade Page</h1>
<p>This is the text of the upgrade page</p>
</div>
<div id="contentachievement">
<h1>Achievement Page</h1>
<p>This is the text of the achievement page</p>
</div>
</div>
</body>
</html>
` I have two questions :
- Is there any way to stop this behavior in javascript?
- In this specific code, how can I refer to the variables initialized in the gameWorld object in the addEventHandlers function? (gameWorld.linkupgrade or this.linkupgrade don't work)