borrame.com - Colección particular de recortes de código y documentación para programación web

Canales RSS

Lo más fresco

  1. Enlaces sobre desarrollo web Modificado
  2. Cadena aleatoria en PHP Modificado
  3. Recortar texto Nuevo

Sugerencias del chef

Lo más visitado

  1. Canales RSS
  2. Formato condicional según el día de la semana
  3. Enlaces sobre desarrollo web
  4. Recortar texto
  5. Convertir de minutos a horas
Compartir esta página

Eventos

Hay una infinidad de maneras de asignar eventos a los elementos de una página web:

Clásica
Código: <body onload="foo()">
Inconvenientes: obliga a modificar el HTML de toooooodas las páginas y toooooodos los elementos donde queremos usar el script. Añadir varios eventos al mismo objeto es un desmadre.
Modernista
Código: window.onload=foo
Inconvenientes: al añadir un evento machacamos todos los anteriores.
Utópica
Código: addEventListener() y attachEvent()
Inconvenientes: cada navegador los implementa a su manera, o de ninguna en absoluto.
Geek
Código: addEvent()
Inconvenientes: falla en algunos navegadores y provoca efectos colaterales difíciles de apreciar a primera vista.

¿La solución?

Dean Edwards nos propone el siguiente código casero (sólo he agregado los comentarios en español):

/* * Gestión de eventos * - http://dean.edwards.name/weblog/2005/10/add-event/ * - http://dean.edwards.name/weblog/2005/10/add-event2/ */ /* * Ejemplo: * * function foo(){ * alert('La página ha terminado de cargar'); * } * addEvent(window, 'load', foo); * * @version 2005-12-06 */ function addEvent(element, type, handler) { // assign each event handler a unique ID if (!handler.$$guid) handler.$$guid = addEvent.guid++; // create a hash table of event types for the element if (!element.events) element.events = {}; // create a hash table of event handlers for each element/event pair var handlers = element.events[type]; if (!handlers) { handlers = element.events[type] = {}; // store the existing event handler (if there is one) if (element["on" + type]) { handlers[0] = element["on" + type]; } } // store the event handler in the hash table handlers[handler.$$guid] = handler; // assign a global event handler to do all the work element["on" + type] = handleEvent; } // a counter used to create unique IDs addEvent.guid = 1; /* * Ejemplo: removeEvent(window, 'load', foo); * * @version 2005-12-06 */ function removeEvent(element, type, handler) { // delete the event handler from the hash table if (element.events && element.events[type]) { delete element.events[type][handler.$$guid]; } } /* * Funciones privadas (son utilizadas por las dos anteriores) */ /** * @version 2005-12-06 */ function handleEvent(event) { var returnValue = true; // grab the event object (IE uses a global event object) event = event || fixEvent(window.event); // get a reference to the hash table of event handlers var handlers = this.events[event.type]; // execute each event handler for (var i in handlers) { this.$$handleEvent = handlers[i]; if (this.$$handleEvent(event) === false) { returnValue = false; } } return returnValue; } /** * @version 2005-12-06 */ function fixEvent(event) { // add W3C standard event methods event.preventDefault = fixEvent.preventDefault; event.stopPropagation = fixEvent.stopPropagation; return event; } fixEvent.preventDefault = function () { this.returnValue = false; }; fixEvent.stopPropagation = function () { this.cancelBubble = true; };

Según nos explica el autor (hay más) funciona en miles de navegadores y no encoge la ropa.

¿Qué eventos podemos manejar?

Un laborioso programador holandés llamado Peter-Paul Koch ha recopiado una lista de eventos en los navegadores más populares. El mismo sitio web contiene información sobre el tema para tomar y dejar.

Esta página ha sido impresa el miércoles 12 de agosto de 2026 (13:52:40 +0200) desde https://borrame.com/recortes/javascript/eventos.html. La última vez que miré contenía HTML válido con CSS fresquito y si tiene flatas de ortografía ha sido sin querer.

Lorem ipsum dolor sit amet.

© 2005-2026 by Álvaro González (alvaro.es) • Burgos (España) • borrame.com