2

I am trying to attach a piece of code to a button OnClick attribute.

// Creating a Button
var btn = document.createElement("BUTTON");

// Append a text to the button

var t = document.createTextNode("random text");
btn.appendChild(t);

// attach the function to the eventLisenter 
btn.addEventListener('click', handleClick);

// function to be executed
var handleClick = function (event) {
    alert("DBZ");
}

The button appears where it belongs, and so does the text in it, however when I press the button the code inside the function won't execute, nothing happens. I have tried running the code in Firefox & Google Chrome.

I have also tried to change the "click" attribute to "onclick" attribute, add/remove bracket of function when attaching and also use the btn.attachNow method. nothing happend really.

Would appreciate any help, Thanks in advance.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
seman
  • 157
  • 2
  • 5
  • 11

1 Answers1

8

You are using a function expression to define your function, and you are doing it after you try to assign your event handler.

Consequently, btn.addEventListener('click', handleClick); is the same as btn.addEventListener('click', undefined);

Move the function definition up your code so it happens first.

Better yet, use a function declaration instead of a function expression.

function handleClick (event) {
    alert("DBZ");
}

Then it will be hoisted and have a useful name when viewed in a debugger.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • great input, I haven't noticed I actually declare a variable therefore i was trying to access an undefined variable, however, why is the function declaration better then then variable declaration that holds a function? is that just sparing the use a pointer to a function? – seman Dec 10 '15 at 17:36
  • Because (a) it is hoisted and (b) it will have a useful name when viewed in a debugger – Quentin Dec 10 '15 at 17:37