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 PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<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>

5 Thoughts Contributed to “JavaScript Tutorial: Hooking Events at Runtime with Parameter Functions”

  1. Mark - March 16, 2009 at 3:29 am Reply

    Hi man, thx for this, it was really helpfull. I was dumb cant figure out this:)

  2. Nrupin - September 4, 2009 at 6:11 am Reply

    Super cool…

  3. Mojtaba - September 16, 2009 at 11:40 pm Reply

    Hi ,

    Its good to know that and I am looking for more advanced thing.
    for example if the event it is already attached by some sort of software that we dont have access to those codes but we are using by including to our scripts and then we want to attach our custom event and at the same time having the old event.
    how we can override that event for example onkeyup to do our action and then calling the old function.

    Many Thanks

  4. Paul Layhew - March 4, 2010 at 8:39 pm Reply

    Hello, I came across this article while searching for help with JavaScript. I’ve recently changed browsers from Safari to Microsoft Internet Explorer 5. After the change I seem to have a issue with loading JavaScript. Everytime I go on a site that needs Javascript, my browser does not load and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix it. Any aid is very appreciated! Thanks

    • Oomph
      Oomph - March 5, 2010 at 11:20 am

      Paul – we’re betting you’re running an old Mac that’s not capable of running a new browser. The short version is, no one supports IE5 for Mac any longer. It’s an antiquated browser, with a 13 year old rendering engine. You’ll probably have other rendering problems throughout the web. If you’re computer is capable, we strongly suggest you upgrade to the latest version of Safari for Mac.

What do you think?

*(required)

Allen Waldrop

By Allen Waldrop

Web Software Engineer

Allen is a locally trained software engineer with a focus on web technologies, including PHP, MySQL, ASP, C#, and SQL Server. He has an uncanny ability to switch from programming language to language with remarkable ease. Allen takes a keen interest in working with web-based system APIs and has recently worked with APIs from Salesforce.com, Google, Acuity, Satuit and Ning to achieve data interoperability between client systems and these third party services.

Read More About Allen Follow on Twitter

Post Meta

Topics

Programming

Tags (Keywords)

,

Oomph is a full-service digital agency providing strategy, design & development and a host of other web services. A leader in WordPress and Drupal implementation, Oomph pushes the boundaries of today’s web platforms. Oomph has a diverse portfolio of non-profits, international corporations and publications. Team Oomph is always thinking creatively about the digital world. Oomph is located in Providence and Boston.