-3

I am trying to loop through an array of html object and add a click event listener to every one of them. Reason for this is CSP.

problem is: it doesn't do it, no errors.. nothing...

Please help before I go insane.

var linkButtons = document.getElementsByClassName("navItem");
for(var i=0;i<linkButtons.length;i++){
  linkButtons[index].addEventListener("click",function()console.log("e.e");});
}
JordyvD
  • 1,565
  • 1
  • 18
  • 45
  • The code you quote has a syntax error - missing `{`. That said, what is the context? Where are you calling this? – Xan Apr 01 '15 at 19:28

1 Answers1

0

function()console -> function(){console and make sure the document is loaded.

Corrected:

document.addEventListener("DOMContentLoaded", function(){
    var linkButtons = document.getElementsByClassName("navItem");
    for(var i=0;i<linkButtons.length;i++){
        linkButtons[index].addEventListener("click",function(){console.log("e.e");});
    }
});
blex
  • 24,941
  • 5
  • 39
  • 72
  • Argh, hahahahhaa can't believe a typo was kicking my ass >.<.. Thanks a lot! – JordyvD Apr 01 '15 at 19:32
  • By the way, any idea on why this only works with the console open? When the console isn't open, the listener doesn't get attached – JordyvD Apr 01 '15 at 19:47
  • I've noticed that in some browsers, the console does not _exist_ when it's closed, and it causes errors. Getting rid of you `console.log`'s or [overriding it so that it works anyway](http://stackoverflow.com/a/17104745/1913729) should solve this. – blex Apr 01 '15 at 19:50
  • I's a chrome app, I don't know if that matters – JordyvD Apr 01 '15 at 19:55
  • In production, minifying your code and getting rid of the logs is best, but if you override your console like the link I posted, it shouldn't cause a problem to keep them. – blex Apr 01 '15 at 20:12
  • Oh, ok, thanks a lot ^_^ I'll try it when I get the chance, the reason I log a lot is to make sure everything works/debugging (I take em all out at the end – JordyvD Apr 01 '15 at 20:40