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 jQuery Basics (2014) Creating a Simple Lightbox Perform: Part 1

Sean Urgel
Sean Urgel
Courses Plus Student 6,650 Points


I'm trying to learn the best way to code JQuery, since this should affect browser loading time, and in programming speed is everything.

So what I'd like to ask which is a better code in terms of speed, re-usabilty, etc. - And how can I further improve on my code.

In this video the code given was

$("#imgGallery a").click(function(event){ event.preventDefault(); var href = $(this).attr("href"); console.log(herf); });

wouldn't it be better if we just create a function and call it like this, making the code more readable, easier to maintain, reusable?

var clicked = function(event){ event.preventDefault(); var href = $(this).attr("href"); console.log(href); }

$("#imageGallery a").click(clicked);

Yes you could do that. However, you need to be careful that you only call the 'Clicked' method on objects that also contain an attribute 'href'

1 Answer

Steven Parker
Steven Parker
230,248 Points

That's a good idea if you need to reuse the function.

But it is very common for event handlers to be unique, and defining them as anonymous functions where the handler is established is generally considered adequately readable. So there's not much advantage to defining the function separately if it won't be used elsewhere.