The problem is that event listeners and "total" both exist in the same scope (init ())
Event functions will always refer to the final value within the init () scope, even if it changes after the event functions are declared.
To get around this, the functions of the events must have a "common" in their field, which will not change. You can add another level of visibility using an anonymous function.
For instance:
(function (total) { div1.addEventListener('click', function(event) { helper(event, total); }, false); }(total)); total += 4; (function (total) { div2.addEventListener('click', function(event) { helper(event, total); }, false); }(total));
Anonymous functions are passed init () current 'total' as a parameter. This sets another βcommonβ in the scope of the anonymous function, so it doesn't matter if init () changes or not, because the event function will FIRST refer to the scope of the anonymous function.
Edit:
In addition, you must place a semicolon after the closing bracket of the helper function, otherwise the script will complain that the "event" is undefined.
var helper = function(event, id) { if (event.stopPropagation) event.stopPropagation(); if (event.preventDefault) event.preventDefault(); alert('id='+id); };
source share