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

Christopher Lebbano
Christopher Lebbano
15,338 Points

I don't understand why this click event is triggered, and getting rid of it seems to make no difference.

Here is the series of videos that my question is related to:

https://teamtreehouse.com/library/jquery-basics/creating-a-simple-drawing-application/perfect

He adds a click even for the $("#addNewColor"), here is the code:

$("#addNewColor").click(function() {
  var $newColor = $("<li></li>");
  $newColor.css("background-color",  $("#newColor").css("background-color"));
  $(".controls ul").append($newColor);
  $newColor.click();
});

The very last line of code... $newColor.click() is what I don't get. Why is it there, and what does it do? When I get rid of the code, the functionality of the final project doesn't seem to change.

1 Answer

Steven Parker
Steven Parker
231,008 Points

:point_right: The last line is intended to select the new color.

But since no explicit click handler was set on this element, this will only work if you have established a delegated click hander for this type of element on one of it's ancestor elements. Since you didn't show the whole code, it's not clear if this has been done, but I would suspect not.

Converting explicit handlers into a shared delegated handler is covered in this video: Perform: Part 3.

Christopher Lebbano
Christopher Lebbano
15,338 Points

When you refer to the shared delegated handler, you're talking about the .on event he used in place of the click?

I still don't see how that event or anything else has anything to do with the line of code $newColor.click().

Is the code supposed to "simulate" a click for the user? Like as if the code is saying "here, lemme click on that for you."?

Hi Christopher,

When you call the click method with no arguments then it triggers a click event for that element. It's a shortcut for .trigger("click")

So as long as you properly set up the event delegation for the list item's click handler you should see that the newly created color is automatically selected.

So when you trigger a click on the new color list item it will execute the click handler for the .controls element.