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

CSS jQuery Basics (2014) Creating a Simple Drawing Application Perform: Part 5

Why is it $canvas.mousedown(...) rather then $canvas[0].mousedown()?

Why are we selecting the array of canvas elements rather the single one on the page?

Also the mousedown method is undefined on the $canvas[0], but not for $canvas (the array of canvas), which doesn't make much sense to me.

1 Answer

Hey Leo Shimonaka,

The reason why we use $canvas instead of $canvas[0] with the mousedown event is because $canvas is a jQuery object which can have functions/methods operated upon it unlike $canvas[0] which is just a reference to that particular element of canvas.

While $canvas as it is initialized would select all canvas elements on the page, it is okay to use that for this project because there is only one canvas element on the page. It would be the same principle even if there were multiple canvases and that particular canvas on the page was given an ID of "drawingCanvas" and we referenced it like so:

var $canvas = $("#drawingCanvas");

If you go into your console in Firefox, and check out the values of $canvas and $canvas[0] you will see two different results returned. Google Chrome returns both variables as the element in console, even though this is not correct.

The $canvas variable will have an output similar to this:

Object { 0: <canvas>, length: 1, prevObject: Object, context: HTMLDocument  port-80-uvzati2deu.treehouse-app.com, selector: "canvas" }

While the $canvas[0] variable will have an output like this:

<canvas height="400" width="600">

I hope that helps!

Perfect, makes sense.

Excellent! Glad I could help, Leo!