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 trialKirby Walls
6,508 PointsHow does the anonymous function get called?
So, following along with the video, I've created this code.
$("#imageGallery a").click(function(event) {
event.preventDefault();
var href = $(this).attr("href")
console.log(href);
});
It's great, it's fine, woohoo! But I'm confused about how the anonymous function I've defined gets called. It's defined here, but never called in the way we learned earlier to call self-executing anonymous functions: by including (); immediately after them.
Is it run because it's an argument for the click method?
1 Answer
Colin Bell
29,679 PointsIn short, click() is an event listener, so the function fires any time an a tag nested within the #imageGallery is clicked.
.click() is a method that listens for a mousedown and mouseup event on the same element. Notice it still has the parentheses at the end. However, in the case of .click(), another function has to go inside the parentheses to make it do anything. The function inside .click() tells the page what to do when it hears the click event.
If you just add .click() without a function inside the parentheses then javascript/jq will basically just be like, "Yup. You clicked that thing."
Kirby Walls
6,508 PointsKirby Walls
6,508 PointsHaha. Okay, that makes sense. The .click() method handles events, so its natural behavior is to immediately do whatever you've defined inside its parentheses because why would you need an event handler that captured events and didn't handle them?
Thanks!