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!

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


Tiffany Haltom
Tiffany Haltom
6,769 Points

Simple Drawing Application pt 11

I have identical code to the instructor, but I keep getting an error: Uncaught TypeError: Cannot read property 'offsetX' of undefined. Here's my code:

var color = $(".selected").css("background-color");
var $canvas = $("canvas");
var context = $canvas[0].getContext("2d");
var lastEvent;

$(".controls").on("click", "li", function() {
  color = $(this).css("background-color");

$("#revealColorSelect").click(function() { 

function changeColor() {
  var r = $("#red").val();
  var g = $("#green").val();
  var b = $("#blue").val();
   $("#newColor").css("background-color", "rgb(" + r + "," + g + "," + b + ")");


$("input[type=range]").on("input", changeColor);

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

$canvas.mousedown(function (e) {
  lastEvent = e;
}).mousemove(function(e) {
  context.moveTo(lastEvent.offsetX, lastEvent.offsetY);
  context.lineTo(e.offsetX, e.offsetY);


What does this error mean and how do I fix it?

3 Answers

It means the lastEvent variable has not been instantiated yet. I'm not sure if this is the best way of solving it, but I declared the variable like this, and the problem went away:

var lastEvent = {offsetX:0, offsetY:0};

Tiffany Haltom
Tiffany Haltom
6,769 Points

well in the code, I instantiate the lasEvent global variable with e. So I'm still not sure why it would say that.

lastEvent = e;

I had the same problem, and just as you I couldn't figure out why this happened. I then assumed the function was somehow executed before the mouse button had been pushed (not sure why it would do that though), and in that case lastEvent would not have been set yet. So I just assigned the expected properties to the variable, since they would be reset anyway when mouse button is pushed.

18,813 Points

If you're using Firefox as your browser there is a fix by John Kay posted quite awhile ago about this problem. You can find his solution in this post.

Your code is running error free for me when using Safari.

Tiffany Haltom
Tiffany Haltom
6,769 Points

yeah. It works fine in Safari and Firefox. Thanks for the suggestion! I thought I was going crazy.