Because cnt
is a local variable in the function you're assigning to onload
, and divHandler
doesn't close over it. It's just like this:
function foo() {
var a = 42;
}
// Can't access `a` here.
Instead, move cnt
out to where divHandler
can close over it — but don't make it a global if you don't have to:
(function() {
var cnt = 0;
function divHandler(e){
++cnt;
document.getElementById("d1_cnt").innerHTML=" clicked "+ cnt + " times...";
}
window.onload=function() {
document.getElementById("d1").onclick=divHandler;
}
})();
Note that the scoping function I've put around that code also makes divHandler
no longer global, as (barring something you haven't shown) there's no reason for it to be.
Or actually, you could just put it all in your onload
:
window.onload=function() {
var cnt = 0;
function divHandler(e){
++cnt;
document.getElementById("d1_cnt").innerHTML=" clicked "+ cnt + " times...";
}
document.getElementById("d1").onclick=divHandler;
};
Side note: The window.load
event happens very late in the page loading cycle, after all images and other external resources are fully loaded (or have failed). You don't need to wait that long to hook up your click handler. Just make sure your script
element is below the markup for the elements you want it to work with in your HTML, and you can hook up the handler right away. The usual recommendation is to put scripts just before the closing </body>
tag, since that means they can access everything above them.
<body>
<div id="d1">Div click me</div><span id="d1_cnt"></span>
<script>
(function() {
var cnt = 0;
function divHandler(e){
++cnt;
document.getElementById("d1_cnt").innerHTML=" clicked "+ cnt + " times...";
}
document.getElementById("d1").onclick=divHandler;
})();
</script>
</body>