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.

2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Because (a) it is hoisted and (b) it will have a useful name when viewed in a debugger

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.