Debugger
Debugger

Reputation: 9488

addEventListener seems not to work

addEventListener is not working, even though i make sure i access the if (the alert works). I am using firefox so no need for now to "attachEvent" for IE...

function addEvent(type,fnName,obj,cap)
{
    if(obj.addEventListener)
    {
        alert("I am 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;

Upvotes: 0

Views: 130

Answers (2)

Christopher Scott
Christopher Scott

Reputation: 2399

There are two immediate issues I see with your code:

  1. JavaScript will throw a ReferenceError because variable nbClicks is not in scope for the function changeBgColor.

  2. You should be assigning strings to the wrap.style.backgroundColor. In this case JavaScript thinks they're more variables, and will throw another couple ReferenceErrors.

Check out this edited version of your code, I encapsulated it all in a closure so all functions have reference to 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;

})();

Upvotes: 2

Serabe
Serabe

Reputation: 3924

it is not working because nbClicks is not initialized in changeBgColor.

var declares a local variable to the function, in this case, init.

if you change changeBgColor to

var changeBgColor = (function() {
  var nbClicks = 0;
  return function() {
     var wrap = document.getElementById("wrapper");
     nbClicks++;
     if (1 == nbClicks )
     {
       wrap.style.backgroundColor = 'lightCoral';
     }
     if (2 == nbClicks )
     {
       wrap.style.backgroundColor = 'lightGreen';
     }
  };
})();

Furthermore, backgroundColor expects a string, not undefined (since those variables were not declared).

Upvotes: 1

Related Questions