Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > HTML/XHTML

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Bind Granular Functions to Events

Listing 1 illustrates one method for binding a function to an event. There is an alternative syntax for attaching functions to events. The <script> tag offers the for and event attributes. The for attribute allows the developer to specify that the script is bound to a certain element, while the event attribute specifies the event that it is bound to. So, Listing 3 is also functionally exactly the same as Listing 1.

Listing 3: Alternative Syntax for Binding a Client-Side Script to an Event

<script language="JavaScript">
 var nCount = 0;        // Executes when document loads
 alert("Count is " + nCount); // So does this
<script language="JavaScript" for="btnIncrement" event="onclick">
 alert(++nCount);       // Executes only when doCount is called
 <input id="btnIncrement" type="button" value="Increment">

While binding functions to events is the preferred method of associating functionality with an event, the trouble with this alternative for doing so is that the entire script block is associated with the specified element and event. This eliminates the capability to leverage a single script for multiple elements. For this reason, the method illustrated back in Listing 1 is preferred.

This preferred method also promotes the use of granular, generic functions as opposed to large, monolithic functions that try to do many things. Code is easier to read, maintain, and reuse if functionality is implemented in smaller pieces.

  • + Share This
  • 🔖 Save To Your Account