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 trial

JavaScript Introduction to jQuery Events Using the on() Method

Arman Taher
Arman Taher
2,019 Points

Why use on('click',function (event){console.log(event)} instead of on('click',function (){console.log(event)}

Why use on('click',function (event){console.log(event)} instead of on('click',function (){console.log(event)}

3 Answers

Alex Warner
PLUS
Alex Warner
Courses Plus Student 4,987 Points

Let’s break this down to make it a little clearer:

  1. You’re calling the .on method and passing it two arguments. The first argument is the type of event to listen for and the second is the function to execute when the actual event fires (in this case a click). This function is commonly referred to as a callback function.

  2. When the event fires JavaScript creates an Event object that contains properties about the event that just fired.

  3. Then the callback function is executed. You don’t have to provide an argument to the callback function but if you want to access any of the information about the event you have to pass the newly created Event object as an argument in your function. You can call it ‘event’, ‘e’, ‘meatball’, whatever you want. The callback function knows that if you provide an argument it represents the Event object.

So: .on( ‘click’, function(e) { console.log(e.type); // ‘click’ }

.on( ‘click’, function() { console.log(e.type); // undefined }

In the second example the Event object wasn’t passed to the callback function so if you reference it within the function definition (ie, e.type) it won’t know what you’re referring to.

Raja Kannan
Raja Kannan
6,590 Points

Hi, function(event) in this event is a parameter. If we use parameter in the function, we have to use it while callling the function also. So, we use on('click',function (event){console.log(event)} instead of on('click',function (){console.log(event)}

Ari Misha
Ari Misha
19,323 Points

Hiya there! Event is an object literal containing all kinds of information. But to access that information in our callback function, we're gonna have to pass it as an argument so that it'll be available in our code block when we need it. Now, the code your provided in your function is basically a simple way of debugging. In the same piece of code, you're just logging out the event object literal in the console.