Wednesday, January 18, 2006

JavaScript Event Handling

The captureEvents() method doesn't have any effect until you assign a function to handle the desired events. To capture all click events on a page, for example, you would need to define a function that handles the event, and then assign the function reference to the event handler. Here's an example:


function processClicks(e) {
// statements to handle the click events
}

window.captureEvents(Event.CLICK); // click is an event
window.onclick = processClicks; // onclick is an event handler

Without specifying a function to handle click events at the window level, all click events would simply be captured at that level, but would not have any influence because a captured event does not proceed to the intended target event handler
------------------------
-- for cross browsers---
------------------------

//FIRST, TELL THE BROWSERS TO REACT TO THE EVENT
if( document.captureEvents ) {
//non IE
if( Event.KEYUP ) {
//NS 4, NS 6+, Mozilla 0.9+
document.captureEvents( Event.KEYUP );
}
}
/* this next line tells the browser to detect a keyup
event over the whole document and when it detects it,
it should run the event handler function 'alertkey' */
document.onkeyup = alertkey;

//NOW CREATE THE EVENT HANDLER FUNCTION TO PROCESS THE EVENT
function alertkey(e) {
if( !e ) {
//if the browser did not pass the event information to the
//function, we will have to obtain it from the event register
if( window.event ) {
//DOM
e = window.event;
} else {
//TOTAL FAILURE, WE HAVE NO WAY OF REFERENCING THE EVENT
return;
}
}
if( typeof( e.which ) == 'number' ) {
//NS 4, NS 6+, Mozilla 0.9+, Opera
e = e.which;
} else if( typeof( e.keyCode ) == 'number' ) {
//IE, NS 6+, Mozilla 0.9+
e = e.keyCode;
} else if( typeof( e.charCode ) == 'number' ) {
//also NS 6+, Mozilla 0.9+
e = e.charCode;
} else {
//TOTAL FAILURE, WE HAVE NO WAY OF OBTAINING THE KEY CODE
return;
}
window.alert('The key pressed has keycode ' + e +
' and is key ' + String.fromCharCode( e ) );
}

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]