Javascript: gestire gli eventi

icon2 Web Mania | icon4 07 23rd, 2008| icon3commenti

Oggi ho trovato un interessante articolo su Javascript e sulla gestione degli eventi. Uno script che secondo l’autore è un po’ datato, ma che pare sia ancora attualissimo.

Non vengono usati prototype, jQuery o altri framework javascript. Solamente un paio di funzioni: addEvent, removeEvent.

function addEvent(obj, type, fn){
if (obj.attachEvent) {
obj[’e’ + type + fn] = fn;
obj[type + fn] = function(){
obj[’e’ + type + fn](window.event);
}
obj.attachEvent(’on’ + type, obj[type + fn]);
}
else
obj.addEventListener(type, fn, false);
}

function removeEvent(obj, type, fn){
if (obj.detachEvent) {
obj.detachEvent(’on’ + type, obj[type + fn]);
obj[type + fn] = null;
}
else
obj.removeEventListener(type, fn, false);
}

Utilizzare le due funzioni è veramente molto semplice:

addEvent(document.getElementById('my_elem'),'click',foo);

Con la chiamata di addEvent, l’elemento "my_elem" avrà un evento legato al click che chiamerà la funzione foo!

via GregWolejko

Hai trovato questo post interessante? Sei un utente twitter? Condividilo allora con i tuoi amici con un simpatico cinguettio semplicemente cliccando il tasto twittami. Grazie.





Potrebbe interessarti anche...

  1. Gestire i CSS in Javascript
  2. La visibilità delle variabili javascript
    In javascript l
  3. Easy Captcha javascript script
    digg_url = 'ht
  4. Un facile CAPTCHA in Javascript
    Volevo proporvi
  5. JS: gestire multi window onload
    Spesso quando c
  6. Stili classi e javascript
    Molto tempo fa
  7. Easy captcha without javascript images and math
    digg_url = 'ht

Related posts brought to you by Yet Another Related Posts Plugin.

Commenti

Puoi tenere d'occhio i commenti di questo articolo col il seguente link RSS 2.0.