Reputation: 41
for(var i=1;i<=s;i++){if(e[r]<0&&n<=0)
{n=Math.abs(e[r])-1;r++}
else if(n>0){n--}else{t=e[r];r++}
var o=document.createElement("div");
o.style.height=t+"px";o.className="thumbnail";
o.id="thumb"+i;
o.setAttribute("onclick","Viewer.goToPage("+i+");");
I'm trying to convert onclick into addEventListener due to CSP restrictions in Firefox OS but not getting success.
Upvotes: 0
Views: 261
Reputation: 147343
You can use addEventListener for this, however I don't see any benefit over direct property assignment (based on adeneo's code):
o.onclick = (function(pageNum) {
return function() {
Viewer.goToPage(pageNum);
};
}(i));
// Presumably o is added to the document before the next iteration
One benefit of this approach is that you can remove the listener later by assigning a new value to the element's onclick property, or add additional listeners using addEventListener (or equivalent).
If addEventListener is used to add an "anonymous" function, there's no easy way to remove it later.
And it's good to avoid setAttribute for attaching handlers as it's inconsistent across browsers. Directly setting the property is supported by every browser back to IE and NN version 3 or earlier.
Upvotes: 0
Reputation: 318182
for (var i = 1; i <= s; i++) {
if (e[r] < 0 && n <= 0) {
n = Math.abs(e[r]) - 1;
r++
} else if (n > 0) {
n--
} else {
t = e[r];
r++
}
var o = document.createElement("div");
o.style.height = t + "px";
o.className = "thumbnail";
o.id = "thumb" + i;
(function(j, elem) {
elem.addEventListener('click', function() {
Viewer.goToPage(j);
}, false);
}(i, o));
}
You'll have to capture the value of the iterator in an IIFE to make it persist in the callback for addEventListener
Upvotes: 1