2
var johnson = button.addEventListener('click', function() {
}); 

In what ways i can use this variable name. can i call the johnson as a function somewhere?

asked Apr 19, 2011 at 13:20
1
  • Missing 3rd argument for addEventListener Commented Apr 19, 2011 at 13:46

3 Answers 3

3

No, because you aren't assigning addEventListener function to the variable, you are assigning the returned value from executing the function (which in this case is actually nothing look here for an example of the return value: http://jsfiddle.net/DKyhW/2/ ).

To assign the function you either need to do:

var johnson = button.addEventListener; 
//this assigns the eventlistener function to the variable.
johnson('click', function () {});

or

var johnson = function () {} //assigns function to variable.
button.addEventListener('click', johnson);
answered Apr 19, 2011 at 13:23
Sign up to request clarification or add additional context in comments.

Comments

3

johnson will contain the return value of addEventListener, but addEventListener doesn't return anything. johnson will be null.

You can certainly used a named function or a variable that points to a function as an event listener, though:

 var johnson = function() {
 //do stuff
 }
button.addEventListener('click', johnson);

Now you can call that listener function by clicking the button, or by calling

johnson();
answered Apr 19, 2011 at 13:23

Comments

2

Since addEventListener does not have a return value, your variable will be bound to undefined being virtually useless.

Maybe you wanted to something like this:

var johnson = function() { ... }
button.addEventListener('click', johnson);
answered Apr 19, 2011 at 13:23

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.