I'm trying to use windows.load without global variable.
The HTML code:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="main.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
Name: <input type="text" id="txt1"><br><br>
<input type="button" value="Check Input" id="b1">
</form>
</body>
</html>
The JavaScript global variable code:
/*jslint browser: true*/
var myButton;
window.onload = function () {
"use strict";
myButton = document.getElementById("b1");
myButton.addEventListener("click",alertMM);
};
function alertMM() {
"use strict";
window.console.log(myButton.value);
}
And finally the NOT WORKING without global variable code:
/*jslint browser: true*/
var myNS = {
myButton: undefined,
//
setUp: function () {
"use strict";
myNS.myButton = document.getElementById("b1");
myNS.myButton.addEventListener("click", alertMM);
}
};
window.onload = myNS.setUp();
function alertMM() {
"use strict";
window.console.log(myNS.myButton.value);
}
The reason that I want to stop using global variable is that I'm afraid it will conflict with future code.
Thanks in advance
Adrian
In:
window.onload = myNS.setUp();
when you define the window.onload
callback, you should assign it the function itself (just myNS.setUp
) so it can be called later. What your code doing instead is calling the function immediately and assigning the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With