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

Click event on <a> or <li>?

Why is it that we add the click event, to the 'a' instead of the 'li'. Cheers Seb

1 Answer

If you had an LI with an anchor in it and you applied your click event to the LI it would do nothing to prevent the anchor from behaving normally, for example, linking to a specific hash or even off site, if you use the anchor on the click event you can actually prevent the default behavior, which gives you more control:

For example, say you had:

  <li><a href="http://www.google.com">Google.com</a></li>


$('li a').click(function(e) {

If you click the anchor, even though it is set to go to Google, in the jQuery we are preventing that default behavior so when clicked it does not leave the site, but the alert still runs. However, if you had the click event only on the LI in this scenario, if you were to click the Google.com link it would take you off site. I imagine that's probably why it was added to the anchor in this case, and not the LI, more control.