javascript - addEventListener seems not to work -


addeventlistener not working, though make sure access if (the alert works). using firefox no need "attachevent" ie...

function addevent(type,fnname,obj,cap) {     if(obj.addeventlistener)     {         alert("i here");         obj.addeventlistener(type,fnname,cap);     } }  function changebgcolor() {     var wrap = document.getelementbyid("wrapper");     nbclicks++;     if (1 == nbclicks )     {         wrap.style.backgroundcolor = lightcoral;     }     if (2 == nbclicks )     {         wrap.style.backgroundcolor = lightgreen;     } }  function init() {     var nbclicks = 0;     var wrap = document.getelementbyid("wrapper");     addevent("click",changebgcolor,wrap,false); }   window.onload = init; 

there 2 immediate issues see code:

  1. javascript throw referenceerror because variable nbclicks not in scope function changebgcolor.

  2. you should assigning strings wrap.style.backgroundcolor. in case javascript thinks they're more variables, , throw couple referenceerrors.

check out edited version of code, encapsulated in closure functions have reference nbclicks:

(function(){    var nbclicks = 0;    function addevent(type,fnname,obj,cap) {     if(obj.addeventlistener) {         obj.addeventlistener(type,fnname,cap);     }   }    function changebgcolor() {     var wrap = document.getelementbyid("wrapper");     nbclicks++;     if (1 == nbclicks ) {         wrap.style.backgroundcolor = 'lightcoral';     }     if (2 == nbclicks ) {         wrap.style.backgroundcolor = 'lightgreen';     }   }    function init() {     var wrap = document.getelementbyid("wrapper");     addevent("click",changebgcolor,wrap,false);   }     window.onload = init;  })(); 

Comments

Popular posts from this blog

php - get table cell data from and place a copy in another table -

javascript - Mootools wait with Fx.Morph start -

php - Navigate throught databse rows -