Handling cross browser JavaScript events

If you want to get what button was pressed and do something with it, read on.

Event handling in web browser are somewhat hard to code, since the different browsers uses different ”standards”. I showed you how to keypresses in different browser in ”Handling cross browser key press events in JavaScript”. To handle events that come from HTML events, like a button press, or an onchange on in a text field, you can do like this:

function handleButton(evt) { var e=evt?evt:window.event?window.event:null; var target=e.target?e.target:e.srcElement?e.srcElement:null; if(target.nodeType==3) target=target.parentNode;// handle Safari bug // Do something with the target: target.value+="BUTTON PRESSED"; }

See the attached example file for a simple implementation.

Further reading: ”JavaScript – Event properties” at QuirksMode.org.