Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialChuong Nguyen
8,256 PointsPerform: Event Handling
In this code: addButton.onclick = addTask; why after addTask there isn't ()?
3 Answers
Vittorio Somaschini
33,371 PointsOk.
If you use the first method you would still need to put parenthesis when calling the function on the click to actually call the function.
With the second piece of code you do not need () as you are setting up a variable called addTask which has the function call inside it so :
if -> function addTask() {...}; we go with: addButton.onclick = addTask()
if -> var addTask = function() {...}; we go with: addButton.onclick = addTask in the second case
I hope this makes it clear.
;)
Vittorio
Henrik Hansen
23,176 PointsWhen adding the parentheses to the .onclick = ... the code will be executed when loaded. The exception to this is when using an anonymous function with the onclick.
// executed when line is loaded:
button.onclick = addTask();
// Executed at the onclick event:
button.onclick = addTask;
// Anon function executed at onclick event:
button.onclick = function () {
addTask();
};
Chuong Nguyen
8,256 PointsThanks for answer.
Vittorio Somaschini
33,371 PointsHello Chuong.
I do not remember the specific case but I guess in this case addTask is a variable and the function call is inside it.
At the top of your code you (and teacher) should have initialized it as a function.
So then we do not need to put parenthesis again.
Is it the case?
Vittorio
Chuong Nguyen
8,256 PointsIn the video, the teacher does present two ways of writing function:
function addTask() {...};
and
var addTask = function() {...};
I think this could be the reason whether () could be added or omitted after addTask in the addButton.onclick = addTask;
What you think?
Chuong Nguyen
8,256 PointsChuong Nguyen
8,256 PointsThanks, your answer is clear and helpful.