Uchenna Ajah
Uchenna Ajah

Reputation: 388

How can I add Event Listener to a function expression

In my html code, i have a button

<button id="btn">Click Me</button>

and a javascript code:

var trial;

document.getElementById("btn").addEventListener("click", tro)

function tro() { 
    if (trial == undefined) {
        alert("Good Programming") 
    }
    else {
        alert("Bad Programming")   
    }
};

If the button is clicked, it returns "good programming". However, with an onclick attribute on my button, I can control the function even in it's anonymous state and get the same result

<button id="btn" onclick="tro()">

Javascript code:

var trial;

var x = function() { 
    if (trial == undefined) {
        alert("Good Programming") 
    }
    else {
        alert("Bad Programming") 
    }
};

but using the addEventListener (without the onclick attribute) for a function expression will do nothing:

var trial;

document.getElementById("btn").addEventListener("click", tro)

var x = function() { 
    if (trial == undefined) {
        alert("Good Programming") 
    }
    else {
        alert("Bad Programming") 
    }
};

How can I add an event handler to a function expression that will successfully execute the code.

Upvotes: 1

Views: 5659

Answers (2)

Amthieu
Amthieu

Reputation: 154

Anonymous function

var trial;

document.getElementById("btn").addEventListener("click", function() { 
  alert(trial == undefined ? "Bad Programming" : "Good Programming");
});
<button id="btn">Click Me</button>

tro function (has to be declared before being called)

function tro() { 
  alert(trial == undefined ? "Bad Programming" : "Good Programming");
}

var trial;
document.getElementById("btn").addEventListener("click", tro);
<button id="btn">Click Me</button>

Upvotes: 0

amedina
amedina

Reputation: 3426

At that point tro function isn't defined. Try to declare it before the addEventListener call and use the x variable:

var trial;

var x = function tro() { 

  if (trial == undefined) {
    alert("Good Programming") 
  } else { 
    alert("Bad Programming") 
  }

}

document.getElementById("btn").addEventListener("click", x);

Why do you have to use the x variable? Because giving a name to a function when you are assigning it isn't equivalent to have a reference to the function object. You are just giving a name to it, but you don't have a reference to it. The reference will be the x variable.

Here you have a codepen.

Upvotes: 1

Related Questions