Set Event Handlers For Row Elements With Prototype

This article describes how to set event handlers for row elements using Prototype. This is especially handy when dynamically creating new elements on a page.

In this example, we have a data grid displayed as a table element. The id of the table is ‘myTableId’. We are going to set up two event handlers for each table row. On a single mouse click event, we’ll call a function that highlights the selected row. On a double click, we’ll call a function that opens the row data for editing. Both of these functions are omitted for brevity.

function setEventHandlers() {
    //get all row elements under element with id ‘myTableId’
    var rows = $$('#myTableId tr');
    rows.each(function(rowElement) {
        rowElement.observe('click', highlightRow);
        rowElement.observe('dblclick', editRow);
    });
}

Once again, Prototype does the dirty work of handling the differences in event handling between browsers. All we have to do is attach an event handler function to an element using the observe() method, and Prototype handles the rest.

Check out the details on the options available on the Event object in Prototype.

Tags: ,

Comments are closed.