1

I'm brushing up on my JS, and I don't know how to ask this, exactly.

I have this:

text_area.onkeyup = function() {
  var text_length    = this.value.length;
  var text_remaining = text_max - text_length;

  feed_back.innerHTML = "<strong>" + text_remaining + "</strong> charactres remaining";
} 

It works. However, should I be able to take the function and pull it out to something like this?

function countDown() {
  var text_length    = this.value.length;
  var text_remaining = text_max - text_length;

  feed_back.innerHTML = "<strong>" + text_remaining + "</strong> charactres remaining";
}

and just call the function by its name?

text_area.onkeyup = countDown();

This has never worked for me, across multiple projects.

Should it? Why doesn't it?

4 Answers 4

4

You'll have to use:

text_area.onkeyup = countDown;

Without the parenthesis.

countDown is a reference to the actual function object countDown. It's simply a reference, and the function won't be called or executed.

countDown() actually calls the function, and evaluates to whatever it returns.

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

Comments

3

It doesn't work because () actually calls the function -- effectively setting text_area.onkeyup to the return value of countDown rather than the function itself.

Try this instead:

text_area.onkeyup = countDown;

Comments

2

The problem is that you're executing the function during the assignment, so the return value from the function becomes attached to the event. Instead you should attach a reference:

text_area.onkeyup = countDown

Or if countdown has parameters you want to pass with it then you can use a function to make sure they don't get lost. Something like this:

text_area.onkeyup = function(){ countDown(paremeter1, paremeter2); }

1 Comment

Thanks for pointing out the function() {...} part. That's really useful.
2

It shouldn't because you're assigning the result of a function call instead of a function reference. Should be:

text_area.onkeyup = countDown;

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.