1

I am trying to get a list of buttons and add event listeners for each of it on domloaded

     window.addEventListener('DOMContentLoaded', function() {  
        var calKeys = document.getElementById("filters").querySelectorAll("a.Button");
        registerKeys(calKeys);
        var registerKeys = function(inputs){
             for(var i=0;i<inputs.length;i++) {
                    inputs[i].addEventListener("click", handleCalcKey, false);
            }
        };
        var handleCalcKey = function(){
             alert( "thi sis a test");
        }
     });

So my registerKeys method basically takes teh inputs and adds the handler. however it fails as uncaught type error undefined is not a function

Not sure what is going on....

4
  • 1
    You know the console (F12) points the exact location of the error ? Commented Jul 28, 2014 at 20:13
  • registerKeys is defined after it's invoked. Commented Jul 28, 2014 at 20:13
  • it fails when it gets to registerKeys Commented Jul 28, 2014 at 20:15
  • a.Button is anchors with HTML class='Button'. Just seeing if you knew that. Also, code is not backward compatible. Commented Jul 28, 2014 at 20:15

1 Answer 1

4

There :

registerKeys(calKeys);
var registerKeys = function(inputs){

you call a function one line before you define it. The variable declaration is hoisted, not the assignation.

You could do it like this :

registerKeys(calKeys);
function registerKeys(inputs){

but it's generally not very readable. Unless there's a good reason (there doesn't seem to be one here), it's clearer when values are given before they're used.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.