JavaScript Tutorial: Hooking Events at Runtime with Parameter Functions

Although there’s a lack of good documentation, adding a function that takes parameters (i.e. Function_Name(Parameter)) to one of JavaScript’s standard ‘On’ events (i.e. ‘OnClick‘ or ‘onKeyDown‘) is relatively simple for JavaScript coders. Advanced programmers might refer to this as dynamic runtime event assignment with functions using parameters passed.

Confused? Here’s a practical example.

Let’s say we have a text area field on a web page, and we want to execute some function every time they make a keystroke inside that field. In our real world example, we wanted to count the number of characters, so we could let the user know how close they were to the limit, and warn them when they exceed the limit. To capture keystrokes, we need to hook into JavaScript’s ‘onKeyUp and ‘onKeyDown‘ events.

Experienced JavaScript developers know that the easiest way to add these hooks is to include them in the HTML for the textarea, like so:

<textarea name="description" cols="50" rows="5"
     onkeyup="function(param1,param2)"
     onkeydown="function2(param1, param2, param3)"></textarea>

But in our real world use case, this wasn’t an option. We were working with a content management system that was generating the field on its own, and changing base code wasn’t an option. We could, however, add some JavaScript code to our template (or theme). So the question arose: how could we add those functions to a textarea we couldn’t change?

Since the textarea field needs to exist before we can hook into it, the JavaScript should be added to the footer, just before the close of the body tag.

The first thing we need to do, as always, is identify the text area we want to work with. Since we only had a “name” attribute to work with (i.e. “description” in the example above), we started with the following code:

<script type="text/javascript">
//get the object we want to modify
var objs = document.getElementsByName('description');
//if the element exists on this page
if (objs.length > 0){
     //objs[0] is the textarea we want, unless there are other
     //textareas with the same name
     var thefield = objs[0];
}
</script>

If your object (the textarea in our example) has a unique ID (let’s say id=”theid”), life is even easier:

<script type="text/javascript">
  var thefield = document.getElementyById('theid');
</script>

Now let’s get to the meat: how do we hook into the object’s events and add our function?

<script type="text/javascript">
//get the object we want to modify
var objs = document.getElementsByName('description');
//if the element exists on this page
if (objs.length > 0){
     //objs[0] is the textarea we want, unless there are other
     //textareas with the same name
     var thefield = objs[0];

     //add function 'Count' with parameters self, and string 'desc'
     thefield.onkeyup=function() { return Count(this,'desc') };
     //add function 'Limit' with parameter self
     thefield.onkeydown=function() { return Limit(this) };
}
</script>

Let’s dissect the new lines in the Javascript above.

.onKeyup – This is the event we want to hook, all standard events are accessible like this depending on the object type (text box, radio buttons, etc). (more on onKeyup)

=function() – This tells JavaScript to attach (=) a function object (that we’re creating on the fly) to the event.

{ return Count(this,’desc’)  }; – “Count” is the name of a function; we’re passing two parameters in this example: the object itself (“thefield”) and a character string “desc”. This will return the result of the function.

Here is a full source, simplified example. In this example, every time the user releases a key in the textarea, a JavaScript alert box will indicate the length of the entered text.

Keep in mind that this very basic example does not account for more complex real world scenarios, like limiting the number of characters. If you need help with more complex scenarios, be sure to contact us.

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script type="text/javascript">
      function Count(taObj,Cnt) {
       alert(Cnt+taObj.value.length);
       return true;
      }
    </script>>
  </head>
  <body>
    <form>
      <textarea name="description" cols="50" rows="5"></textarea>
    </form>
    <script type="text/javascript">
      var objs = document.getElementsByName('description');
      if (objs.length > 0){
       objs[0].onkeyup=function() {return Count(this,'Length: ')};
      }
    </script>
  </body>
</html>