main.html:
<script src="main.js"></script>
<input type="button" id="test" value="click here"></input>
<div id="display"></div>
main.js:
var button = {
counter : 0,
click : function() {
button.counter++;
document.getElementById("display").innerHTML = button.counter;
}
};
window.onload = function()
{
var b = document.getElementById("test");
b.addEventListener("click", button.click, false);
}
Important notes:
Without this onload function, putting 'addEventListener()' directly in global scope will give error, because we are attaching <script src="main.js"> before the <input type> for 'test'. So, JS will not get this element in DOM tree. hence, onload function will wait till document is not getting loaded fully and all elements are available in DOM tree.
<script src="main.js"></script>
<input type="button" id="test" value="click here"></input>
<div id="display"></div>
main.js:
var button = {
counter : 0,
click : function() {
button.counter++;
document.getElementById("display").innerHTML = button.counter;
}
};
window.onload = function()
{
var b = document.getElementById("test");
b.addEventListener("click", button.click, false);
}
Important notes:
Without this onload function, putting 'addEventListener()' directly in global scope will give error, because we are attaching <script src="main.js"> before the <input type> for 'test'. So, JS will not get this element in DOM tree. hence, onload function will wait till document is not getting loaded fully and all elements are available in DOM tree.
No comments:
Post a Comment