oscilatingcretin
oscilatingcretin

Reputation: 10919

How to wire up an event to an HTML element in Javascript?

I am having difficulty finding a cross-browser-compatible, Javascript-based method to attach a function to an element. It seems that Microsoft (of course) has its own way of doing things yet once again and is making it difficult to do this. Basically, I am creating a table dynamically in Javascript and am adding TEXTAREA elements to cells in the row. I need to add a function to the onkeydown for the TEXTAREA so I can check whether or not the length of the textbox has reach a max limit (TEXTAREA elements don't support a MaxLength property unfortunately).

Does a simple solution to this exist that works for FF and IE6, IE7, IE8, and IE9?

Upvotes: 0

Views: 2584

Answers (3)

Michiel Overeem
Michiel Overeem

Reputation: 3982

I would suggest that you take a look at jQuery. An example would then be

$('textarea').keydown(function () { });

Note that in this example I attach the eventhandler to every textarea. A better way would be to use css classes or another more specific selection to find the right textareas. For example:

$('textarea.limitedlength').keydown(function () { });

Also note that you should do this after creating the element. If you do not want to bother with timing, use the live function, jQuery will then attach the eventhandler to any new found element.

$('textarea.limitedlength').live('keydown', function () { });

The benefit is that any cross-browser problems are handled by the framework. (I'm not aware of any cross-browser problems with the keydown event, but jQuery handles the differences in setting up event handlers and selecting the right elements).

As RobG notes in his answer, the keydown (and keyup events) aren't enough, because of pasting. Another approach would be to count and check when the focus is removed from the textarea:

$('textarea.limitedlength').blur(function () { });

Upvotes: 1

RobG
RobG

Reputation: 147403

The problem with using key events to check on textarea content is that there are other ways of entering text, such as paste or drag. Many use setInterval or setTimeout to check on the content and update the count from time to time (say 50ms), but such approaches can be computationally inefficient. You might be able to have the timer running only when the textarea has focus.

There is also the HTML5 input event type that fires whenever a form control has input:

<textarea oninput="document.getElementById('msg').innerHTML = this.value.length;">
</textarea>
<div id="msg"></div>

But of course not all browsers support that.

Upvotes: 1

gilly3
gilly3

Reputation: 91497

Unless you need to attach more than one event listeners, this works fine:

element.onkeydown = function(e)
{
    e = e || window.event;
    ...
}

Upvotes: 0

Related Questions