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:
javascript throw referenceerror because variable nbclicks not in scope function changebgcolor.
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
Post a Comment