Listening to multiple events

Does anyone know of a good tutorial that shows an example of a Javascript function listening for more than one events? Such as listening to multiple events?

All the examples that I have been able to find were ones that listen to only one event.

Thanks in advance.


function foo() {
    alert(5);
}
myDiv.onclick = foo;
myDiv.onmouseout = foo;

The function isn’t really the thing that does the listening. Probably better to think of the element as the listener.

edit- most of the time though, you probably want to do something different in response to a different type of event, so you usually use a different function. But, if you really want to, you could use the same function, and then have the function inspect the event.type to decide what it should do.

You would use the following to add an event listener.


function addEventListener(el, type, fn) {
    if (el.addEventListener){
        el.addEventListener(type, fn, false); 
    } else if (el.attachEvent){
        el.attachEvent('on' + type, fn);
    }
}

This allows you to trigger different functions, even for the same event, which can be useful when you want to validate a field, as well as something else.


function validate() {
    // ...
}
function doSomethingElse() {
    // ...
}

var el = document.getElementById('myForm').elements.username;
addEventListener(el, click, validate);
addEventListener(el, click, doSomethingElse);