New terms from treehouse – AJAX Basics Part 1 – AJAX Concepts and Programming AJAX

AJAX stands for Asynchronous JS And XML. It lets you update html without loading a new webpage. Examples include when you load google maps, then search for a new location and the map/ui change. Or, in twitter with it’s endlessly loading tweets as you scroll down. Or, when you upvote something on reddit.

Normally, you get more web content by loading a new webpage. AJAX is faster and easier, the web page requests info from the web server (the Request), which then returns the data to the web browser (the Response), which JS then uses to selectively change parts of the web page. The amount of data returned is usually much less than a full web page.

To see a pages AJAX requests, open the JS console > right click > Log XMLhttp requests. XHR is short for XML http requests. AJAX isn’t actually its official name. Technically it’s called the XMLHttpRequest Object, or XHR. Example: you sign up for a newsletter, the page sends a request and the server does something, like adds your email to a database, then sends a response which makes the page display a “success” message.

JS is the programming language used to make AJAX happen. It’s used to send out a AJAX request, process the incoming response, then also to update the page. The asynchronous refers to how the request is sent to the server. They are sent without waiting, otherwise they would freeze your browser until you got a response back  (which might not even happen). With asynchronous, the page continues loading regardless. This let’s you send out multiple requests, and you won’t know which will come back first. They’re affected by the speed of the server, the complexity of the request and any internet traffic. XML stands for extendable mark up language.

There are four steps.

1. Create an XMLHTTP object – tells the web browser to get ready, you want to send an AJAX request and the browser needs to create an object that has all the methods needed to send and receive data.

2. Create a callback function – This is the programming you want to run when the server returns its response. The callback is where you process the return data, and update the HTML on the page. This is the heart of AJAX.

3. Open a request – here you give the browser two pieces of information, the method the browser will use to send the request (usually GET or POST), and the URL where the request is sent.

4. Send the request – The last three steps gave the browser everything it needs, so we can finally send the request.

A simply AJAX example

You can just use AJAX locally. You’ll need to set up a web server either locally or a normal one.

We start by writing JS. Step 1 – make XMLHTTP object – We declare a variable and set it to new XMLHttpRequest(). You need to do this for each request you want to send. So if you wanted to send two, you’d need two variables, each with their own XMLHttpRequest()’s.

Screen Shot 2014-10-10 at 1.29.47 PM

Step 2 – create a callback function –  This uses and event listener similar to what we saw before for mouseclicks, scrolling, keypresses etc, and is .onreadystatechange. It runs its function each time there is a change in the state of an AJAX request, which can be sending the request, receiving the response,  etc. The readyState property on the XMLHttpRequest() object holds a number 0-4 showing the current state of the request, and when it’s done, that number is 4. We then create an if block that reads true if the state is 4.

Then, we want to enter the html received by the server into a div, which we can do with document.getElementByID(‘ajax;) and set its innerHTML property, which contains all the HTML inside it, and by changing its value we change the html inside it. So, we’ll set that equal to xhr.responseText. Every XML HTTP request object has a property called response text, which is the information the server sends back. So, we’re taking that and setting it equal to the innerHTML, so it will become the div’s html.

Screen Shot 2014-10-10 at 1.39.56 PM

Remember, the programing won’t run until the response comes back from the server.

Step 3 – open a request – xhr (the variable we’re calling our XMLHTTP object) has a function called .open, which you give two pieces of information, the http method, and the url you want it to go to, which can be a file, etc. In the example below we’re getting the sidebar.html file.

Screen Shot 2014-10-10 at 1.45.58 PM

Step 4 – sending the request – here we use the send() function. Since we’re requesting info (GET), we don’t need to provide the function with anything, but if we were sending stuff (POST, PUT), we would need to.

Screen Shot 2014-10-10 at 1.47.00 PM

This isn’t very interactive though. Let’s make it so it loads upon clicking a button. First we’ll add the button to the markup, give it an id and set it’s onclick attribute to a function sendAJAX().

Screen Shot 2014-10-10 at 1.51.58 PM

Then we’ll create the function and make it so when the function runs it send the request, and also so that the button itself disappears. Note how the latter is different than jQuery, where you would just use .hide(). Here you need to select the display property and set it to “none”.

Screen Shot 2014-10-10 at 1.55.12 PM


Opening a request requires specifying the method you want to use to send the request. GET is used when you only need to receive info from a server. Use POST when you need to send info, like a reddit vote or an email sign up for a newsletter. When you go to a website, the browser actually uses a GET to get the web page.

However, usually things need to be dynamic and have you send and receive info, like when using google maps, you put in your address, it updates the map, etc. You can do this with GET and its url. The part after the question mark is called a query string. It lets you send additional info that the web server can use to control the output of its response. Commonly it’s used to search a database of info and return a single record or a small subset.

Screen Shot 2014-10-11 at 7.27.05 PM

Query strings are made up of one or more name/property value pairs. You separate them with ampersands (&).

Screen Shot 2014-10-11 at 7.28.57 PM

There are rules on what characters you can use. &, space, quotes and + have special meanings in a URL so if you want to use them you have to encode them, which translates them into a set of safe symbols that won’t conflict with their normal meaning.

Screen Shot 2014-10-11 at 7.31.20 PM

There are sites online to help you with this, like this one.

Screen Shot 2014-10-11 at 7.32.47 PM

Now, an issue with doing this is that all the info needs to be sent via the url, which is bad if it’s sensitive data. It’s not very secure as it will show up in the servers log files. Also, there is a char limit for urls in some browsers.

The POST method is better for sending large amounts of info. Rather than sending the info in the url like GET does, it puts it in the body of the request, separate from the url. It also requires a special header for the request, which is a special instruction to the server telling it what type of data to expect.

AJAX Response Formats

It can be a text message, like “OK”, or “Message Received”. Or it can be a static file, which is one just sitting on the server, like the bit of html we got in the practical example above.

But what if you get a lot of data? It’s good to have a structured format. This means it’s ordered consistently, has identifiers that indicate what the data is, and is easy for JS to analyze and use. The process of breaking a file up into easily accessed parts is called parsing. Two common formats are XML and JSON.

XML is extensible markup language, which apparently let’s you make up your own tags. That shit cray.

Screen Shot 2014-10-11 at 7.44.41 PM

However, XML is tough to use with JS, so we use JSON instead.

AJAX Security Limitations

It’s limited by the browsers same origin policy, which controls how JS can access content from a web server. In general, you can use AJAX to communicate from one page to another on the same web server, but not to access other web servers. If you try to request info from a different server than the one the site is hosted on, it’s another origin and it’s forbidden. Or, if yours is http and that one is https, it’s not allowed. You also can’t do one with a different port than yours. Or, one with a different host, meaning vs

Screen Shot 2014-10-11 at 7.54.48 PM

But what if you want something on your site from a different one, like a google map or a tweet? There are a few ways to circumvent the same origin policy, like a web proxy. Web servers aren’t limited by the same origin policy, so you can have your server ask for info from another one using php or ruby.

Screen Shot 2014-10-11 at 7.57.18 PM

Another way is JSOPJSON with Padding, where you basically link to a JS file across another domain. An example is jQuery. Instead of actually using AJAX to contact another web server, you load a JS file from the other site.

Screen Shot 2014-10-11 at 8.01.13 PM

Finally there’s CORSCross Origin Resource Sharing, which is a W3C recommendation. It requires some set up on the server’s part, but it allows a server to accept requests from other domains. It also allows for more complex forms of authentication, requiring the web browser to supply credentials before the server will provide any info.

Screen Shot 2014-10-11 at 8.04.09 PM

Last limitation – AJAX won’t work unless you’re viewing the page via a web server.

Programming AJAX

This project will have you add a sidebar to your companies intranet that says whether an employee is in or out of the office.

AJAX Callbacks

Remember, the readyState property can be 0 to 4, with 0 being when the XMLHttp object has been created, with 3 being when the response is coming, and with 4 being the server has sent everything it’s going to send for the response. In our previous example, we set the callback function to run when the readyState was 4, but sometimes that’s not enough, something may have gone wrong. The web server can’t connect to the database, the web program handling the request crashes, or the AJAX pointed to a file that can’t be found. If any of these happen the browser won’t receive the response with the info needed.

So, we can expand the conditional statement by checking another property of the request object, the status property,which is a number sent from the server telling you about how things went.

Screen Shot 2014-10-12 at 3.19.41 PM

  • 200 means okay, and is the standard response for a successful http request
  • 404 is for file not found
  • 401 is not authorized to access a url due to a log in requirement or permission needed
  • 500 is when the server has an error, usually when its programming isn’t working.

So now nothing happens unless we get the response and the request is sent successfully. But, you can adjust it for if things go wrong.

Screen Shot 2014-10-12 at 3.22.42 PM

Accompanying the status object is the statusText, which is an explanation of the status. You can use this as part of the error message you display to the user. Here, we’ll use an else block to make it so that anytime you get something other than a 200 message, it gives an alert error message. To test this, we’ll change the .open to look for a file that’s not there.

Screen Shot 2014-10-12 at 3.25.50 PM

Screen Shot 2014-10-12 at 3.26.58 PM

In some cases, you won’t need any error message.

Introducing JSON

JSON stands for JavaScript Object Notation and is a way to use JS to pass info around. It uses basic JS objects and arrays to store data, and you can format it in two ways, using an array and/or object notation. An array is a comma separated list of values in square brackets. The problem with arrays is that you don’t know what the data means. Like what is the string for? Why is the third item true?

Screen Shot 2014-10-12 at 3.57.07 PM

An object is made up of key value pairs which fixes this. The key is the name of the property, and then you set its value. The key is separated from it’s value by a colon, and you separate the pairs with commas, except for the last one.

Screen Shot 2014-10-12 at 4.00.53 PM

While this look just like the objects we did with JS, there is an extra requirement for JSON formatted data. In regular JS, keys don’t have to be quoted, but in JSON they do and require double quotes. Also, strings require double quotes as well.

Now to get to work on the project. We’ll create an array, and then put objects into the array, since objects are just as valid as strings, numbers, etc for an array. JSON is picky, so if you mess up with the formatting, you’ll usually end up with a JS error. You can use an online validator to check your JSON, like this one. You won’t ever really have to write JSON by hand, it’ll usually be written programmatically by the web server.

Parsing JSON

Even though JSON is formatted to look like JS, it isn’t – it’s a plain text string, with no significance to your web browser. We need to take it and convert it into JS, a process known as parsing. All web browsers can do it using one command.

We’ll start by creating a XMLHttpRequest object, and then set up the callback function to run when the readyState property is at 4. Then we’ll do our steps 3 and 4 to open the request and then send it.

Now, let’s set up the actual code for the callback function that we want to run. We’ll get the responseText property of our xhr object, and set it in a console.log so we can see what it actually is saying. We then link our js file to our html one in the head, and we get this when we run the page.

Screen Shot 2014-10-12 at 4.26.45 PM

Screen Shot 2014-10-12 at 4.26.06 PM

In the console, you can see it loaded our file. It looks like JS, but it isn’t yet. We can check this using the typeof operator, which looks at the type of the thing list after it.

Screen Shot 2014-10-12 at 4.28.56 PM Screen Shot 2014-10-12 at 4.28.51 PM

To turn it into real JS, use the JSON.parse method, which takes a string and tries to convert it into a JS object. Remember, JSON is picky and this won’t work unless it’s formatted correctly. You’d get a JS error.

Screen Shot 2014-10-12 at 4.32.39 PM

To check this, let’s first see the type of element the employees variable is.

Screen Shot 2014-10-12 at 4.34.18 PM Screen Shot 2014-10-12 at 4.34.14 PM

Note – in JS arrays are considered a type of object. Next, let’s see whats inside the object.

Screen Shot 2014-10-12 at 4.35.56 PM Screen Shot 2014-10-12 at 4.35.48 PM

Processing JSON

Ok, we start by looking at the final html/css we’ll want. It’ll be a simple unordered list, and if they’re in, they get a class of in, and if they’re out they get a class of out. We’ll use the before and after pseudo-classes to display the icons. To build the html, we need to generate from the JSON one list item for each person in the company.

Screen Shot 2014-10-12 at 4.42.06 PM

Screen Shot 2014-10-12 at 4.43.17 PM

We’ll start by declaring a variable, and setting it equal to an opening ul tag. Next, we’ll build it up by adding more html to the variable, then eventually print it to our webpage.

Screen Shot 2014-10-12 at 4.45.52 PM

Now we’ll create a for loop to run through the list of employees. It starts by setting a counter variable, i, to zero. The second is a test condition which will determine how many times the loop runs for. As long as i is less than the length of the employees array, the loop with continue to run. Lastly, after each time the loop runs, 1 is added to the variable i.

In an array you use the index to access each value. Rather than type that in ourselves, we can use the counter variable i from the loop.

Screen Shot 2014-10-12 at 4.51.27 PM

To access properties in JS objects we use the dot syntax aka dot notation. Simply write the object, then a dot, then the property name. As i’s value changes, we’ll access different objects from the array.

Screen Shot 2014-10-12 at 4.53.23 PM

Screen Shot 2014-10-12 at 4.54.05 PM

Now, let’s start by checking if the employee is in the office with an if/else block, and add a opening tag list item with the appropriate class. The += operator in JS means take the current operator and add something to it. Next, we’ll add the name, and then close the tag. By the time the loop is done, it’s been filled with the list items. We can then add it to the div that’s already been set up to hold it.

Screen Shot 2014-10-12 at 6.20.10 PM Screen Shot 2014-10-12 at 6.19.59 PM

They had me do another challenge where we did basically the same thing only with whether rooms were taken. Note – with each new variable you declare for xhr objects, you need a new variable name.

Screen Shot 2014-10-12 at 6.38.10 PM Screen Shot 2014-10-12 at 6.37.26 PM

New terms from treehouse – jQuery Basics Part 2 – Mobile Drop Down, Password Confirmation and Drawing App Projects

Creating a Mobile Drop Down Menu

We have a site with a top nav that doesn’t look good on mobile. Highlighted to show some of the links go missing.

Screen Shot 2014-09-29 at 1.40.33 PM

Here is our current problem/solution and psuedocode gameplan:

Screen Shot 2014-09-29 at 1.52.44 PM

We’ll start by created a detached (aka disembodied) element for the select element. Then we’ll append it to the menu div, and check to see if it worked (it did).

Screen Shot 2014-09-29 at 1.57.49 PMScreen Shot 2014-09-29 at 1.57.54 PM

Now we need to cycle over the menu links, so we’ll select those with “#menu a”. This is better than div a because it’s more specific. To cycle over them, we should look under the traverse section, and choose the each() method, which let’s us iterate over a matched object, executing a function for each matched element.

We’ll start with a disembodied element $anchor which simply refers to the link, the create an option element using one as well, calling it $option. We’ll then set the option’s text to that of the link’s using the text() method twice, once to set and once to get: $option.text($anchor.text());. Then, we’ll add these new options to the select element using  $select.append($option);. Finally, we’ll set the value attribute of the option element using the val() method listed under attributes. So we’ll write $option.val($anchor.attr(“href”);, which is saying, set the value attribute of option to the value of the href attribute on the anchor element.

Screen Shot 2014-09-29 at 2.25.44 PM Screen Shot 2014-09-29 at 2.26.10 PM

Now, we’ll create a button and append it to the #menu div using the same disembodied element way as before.

Screen Shot 2014-09-29 at 2.29.58 PM

Next we’ll bind a click handler to that button using ${});. Now we need to make it go to the select’s location when clicked. We want to use the value of the value attribute for the $select objects, so we can use the val() method again, this time as a getter because we’re not passing in any parameters. We’ll then use window.location, which is how Javascript let’s you change the windows location, and set it to that.

Screen Shot 2014-09-29 at 2.36.42 PM

Now, when you choose the option from the drop down and click the Go button on the right, it takes you to the selected page.

Screen Shot 2014-09-29 at 2.37.03 PM

Password confirmation project

Here we have some pop ups for when you put in your password wrong that we only want to show during certain conditions. Here’s that and the pseudocode gameplan:

Screen Shot 2014-09-30 at 4.13.39 PM

We start by hiding the spans.

Screen Shot 2014-09-30 at 4.16.26 PM

Now we need to select the password input when someone is writing in it. We’ll select it using the id on the input element, “password”. Then we’ll use the focus() method, under Events > Form Events, which occurs when you click on an input field, giving it focus. It accepts a handler, which is an anonymous or named function.

Screen Shot 2014-09-30 at 4.22.04 PM

We’ll then use the val() method again, which works for select, textarea and input form elements. It returns a string, and strings in JS have a property called .length, which returns the length of the string, so we’ll put that at the end of it. We’ll then set that > 8 and we now have our parameter for our if/else block.

Screen Shot 2014-09-30 at 4.26.24 PM

We now need to traverse the DOM a bit, because we’re trying to show/hide the span that comes after the input.

Screen Shot 2014-09-30 at 4.28.05 PM

The next() method under traversing the DOM let’s us do that. We add this in to show and hide it.

Screen Shot 2014-09-30 at 4.31.57 PM

But this doesn’t work. Even if we write 9 characters, it doesn’t disappear until we give it focus again. What we really need is a method that binds the event (what triggers the function) handler (its function) to when you’re done with your keypress: keyup(). We’ll add this to the end of our current thing, but rather than do the same code twice for hiding and showing, we’ll just make that into our own named method for later use, calling is passwordEvent. Now it works!

Screen Shot 2014-09-30 at 4.38.42 PM

Now to do the confirmation password, which has an id of confirm_password. Since the solution here will probably be similar, we’ll start by getting another function ready, confirmPasswordEvent. We need the event to happen on confirmation input, so we’ll set that up the same way too.

Screen Shot 2014-09-30 at 4.58.42 PM

Now we need to find out if the confirm password is equal to the first password.

Screen Shot 2014-09-30 at 5.02.28 PM

But this is starting to get a bit messy, so we’ll make some variables for them, which allow us to use them instead and also replace all the $(this)’s from the last function.

Screen Shot 2014-09-30 at 5.05.05 PM

We now need to show and hide the hint, so we can do just what we did before with next() and hide/show().

Screen Shot 2014-09-30 at 5.08.04 PM

But what if our passwords match, then we go back and change the first password? The confirm hint should show up again because they don’t match, but it won’t unless we focus on it or keyup. We can do this by calling the confirm password events on the first password object as well.

Screen Shot 2014-09-30 at 5.13.29 PM

A good thing to note – we can use focus() twice with different event handlers and they don’t mess with each other. So when we focus on it, it’s doing both focus() methods, not just the first one. It’s good we made them variables as well, because using $(this) would have messed this up.

Time to perfect this by making the submit button invalid if the password isn’t long enough or if they don’t match. So, we want to add the disabled boolean attribute to the submit input element.

We’ll start by making two functions, one to check if the first is 8 characters and the second to check if they’re matching. For the first one, we can actually replace the first part of the passwordEvent one in the if block, since it will be returning that and is the same thing.

Screen Shot 2014-09-30 at 5.37.09 PM

What’s nice is that if there are other conditions need later for the password (like 1 cap 1 number, etc), we can just add them to the isPasswordValid() function now.

We’ll do the same thing for whether they’re matching.

Screen Shot 2014-09-30 at 5.39.31 PM

Now we’ll make a function for whether it can submit or not. Remember, return with something after will return true or false.

Screen Shot 2014-09-30 at 5.42.03 PM

Now we need a function to enable or disable the submit event. An exclamation point means “not”, so !true = false and !false = true. In the function, we’re selecting the submit button, the we’re changing the “disabled” property based on whether the canSubmit() returns true or false. However, right now if it’s true, which means the button should be good to submit, it would return true and add the disabled property. We want the opposite, so we put in !canSubmit(), which flips those values.

Screen Shot 2014-09-30 at 5.49.00 PM

Now we can add that to our previous code, with keyup() at the end of each.

Screen Shot 2014-09-30 at 5.51.52 PM

However, if we just click submit as soon as the page loads, all this doesn’t work because it’s dependent on a keyup event in the password or confirm inputs. So, we need to execute it when the page loads. So, we simply put this at the bottom.

Screen Shot 2014-09-30 at 5.56.05 PM

Simple drawing application project

We should always aim for our projects to work without JS, this is called graceful degradation. 5 of the 6 projects we’ve done here do that, except for this one, but we don’t really have a choice as there’s no other way for us to get it working. Here’s the problem/solution and pseudocode game plan:

Screen Shot 2014-10-01 at 3.11.12 PM

First is to get the color selector working. We’ll use the click() method. We should also create a variable for the .selected color, as we’ll likely be using that a bit for other stuff. We select it using the .selected selector, then we need its color property so we’ll use the .css() method.

Screen Shot 2014-10-01 at 3.18.59 PM

We’ll probably want to cache the current color, so we can copy that code and put it in the function, using (this) instead for the selected color. Now, to deselect the sibling elements, we’ll first use this, for the thing we clicked, followed by the .sibling() method, which selects its sibling elements, then finally we can use the .removeClass() method to remove the specified .selected class from them.

Screen Shot 2014-10-01 at 3.25.07 PM

Then, to add a class we simply use this and the addClass() method, and we’re good to go.

Screen Shot 2014-10-01 at 3.30.25 PM

Now to make the new color button work. We want to hide or show the color selector when you click the button, based on whether it’s hiding or showing at that time. The show and hide methods aren’t the best option for this, you should use the toggle() method. With no parameters, it simply toggles the visibility of elements. So, we’ll set up a click method on the button, and the toggle method on the colorSelect div.

Screen Shot 2014-10-01 at 4.02.37 PM

Now to update the color span when the sliders change. We’ll start by creating our own method called changeColor, which will change the background-color css property of our selected #newColor span. Then we need to select the range inputs, the sliders, which we can do with attribute selectors. We then use the on() method that says, on an input (which is when you move the slider in this case), it triggers the handler, which in this case is our changeColor function.

Now, in our changeColor() method, we created a variable for each of the color sliders, that takes their value, which is where the slider is at. We then did some math with the css() method that added the three variables together to give us an rbg value, which is what is set as the background color for the #newColor span. It starts as black when we click the new color button because all the sliders are at 0, making it black.

Screen Shot 2014-10-01 at 4.22.20 PM

Now we need it to actually add the new color when you click the Add color button. We’ll start with the click method on the selected button, then create a disembodied list item element. We then want to alter that new color’s background color using the css() method. For the value we’ll use the $(“#newColor”).css(“background-color”) created from the previous method above. We’ll then append() it to the ul list in the div with the.controls class. We’ll then try and make it select it with a click() method.

Screen Shot 2014-10-01 at 5.32.12 PM

Issue – the color gets added (yay!) but doesn’t get selected. The issue is because the click listener we created earlier that switched the selected color on picking one, when the page loads, it binds the click handler to the existing ones, and ignores any new list items. We need a method that will bind when the page loads but also for any future things elements added. The on() method let’s us do that. First we set what happens, the click, then the child element we want it to happen to, the “li”, then we set the function that runs when that happens.

Screen Shot 2014-10-01 at 5.40.29 PM

Ok, finally we get to make the pencil draw stuff. This works via the HTML5 canvas element. First we select the canvas element using jQuery, then we’re actually going to select the canvas itself instead of the jQuery representation of the canvas, and we do this by writing [0] after it. This is actually the same as writing document.getElementByTagName(“canvas”)[0], only easier to write/read. The reason we do this is because the actual element has a special method we can call on that element, which is to get its context – .getContext().

Context in 2d and 3d graphics is just a way for the computer to know where to draw. We’ll set the value to “2d”. We’ll then save this as a variable. Online you may see it named ctx, which is short for context. Finally we’ll move it to the top so we can cache it as a variable when the page loads.

Screen Shot 2014-10-01 at 5.48.47 PM

Now for the drawing code. We’ll start with the context variable, then the beginPath() method, which is saying in the context we want to start a path. We then use moveTo() to say the distance we want it to move on the x and y coordinates, in px. This will be our starting point. Then we use lineTo() to say where the line will go. If we write 20, 10, it will move on the x axis ten px. This is the ending point. Finally, we use .stroke(), and get this:

Screen Shot 2014-10-01 at 5.53.48 PM Screen Shot 2014-10-01 at 5.53.44 PM

To draw a square, we just add more lineTo’s. For the last line, we can use a method called closePath(), which will close things up for you.

Screen Shot 2014-10-01 at 5.56.21 PM Screen Shot 2014-10-01 at 5.55.09 PM

Now to make the pencil do this. When you draw, you don’t just click, you click and hold the mouse down, the let go, so we’ll use the mousedown()mousemove()  and mouseup() methods, in that order. First we’ll select the canvas and cache it as a variable, putting it at the top of the page.

Screen Shot 2014-10-01 at 6.17.50 PM

We’ll apply the mousedown() method to the $canvas object. Just like keyboard click events, there is an event object that can be passed into the handler. When we click down with a mousedown event, it gives us the coordinates. To save this, we’ll first create another global variable, lastEvent. Then in the mousedown() method we’ll pass in e and set lastEvent equal to that. When we check it in the console, we can see a bunch of properties for it now, based on where we clicked. This includes the offset x and y, which we’ll use in our drawing code.

Screen Shot 2014-10-01 at 6.20.16 PM

Screen Shot 2014-10-01 at 6.19.34 PM Screen Shot 2014-10-01 at 6.18.51 PM

Now we need to write what happens when the mouse is moved while being held down. When can chain the mousemove() method onto the one we just wrote, and will pass in e again. We can use the same code we used before with some tweaks. We’ll leave in beginPath, and for moveTo, which remember is the offset, well pass in the lastEvent variable with its properties for the x and y offsets. Now for the lineTo, which draws the line, we do e.offsetX and Y. We can then remove the other lineTo’s and the closePath as they’re not needed.

With the current code, we get this:

Screen Shot 2014-10-01 at 6.27.08 PM Screen Shot 2014-10-01 at 6.27.01 PM

So we’re still drawing even when the mouse is up. What we need to do is update the last event so it stops drawing on mouseUp(). First we’ll set lastEvent to e again, which makes it at least follow the cursor. We want to store if a mouseDown has occurred, so we’ll create a variable for that, and set it to false. Then in our code below, we’ll set it to true. We’ll then use this to make an if block for the drawing code, which will only be true (and therefore running) when the mouse is down.

Screen Shot 2014-10-01 at 6.30.37 PM Screen Shot 2014-10-01 at 6.33.05 PM

Now we get to add on the mouseup() method. We’ll add it in and make it so that it causes the mouseDown variable to be set to false, stopping the drawing.

Screen Shot 2014-10-01 at 6.36.10 PM

Now to make it actually use the selected color. We do this with the strokeStyle property for context, and setting it to our color variable from before.

Screen Shot 2014-10-01 at 6.40.09 PM

One last issue – when you draw outside the canvas and come back in, a line appears.

Screen Shot 2014-10-01 at 6.44.45 PM

The mouseleave() method binds an event handler to when the mouse leaves a an element. We’ll the make the function simply trigger the mouseup() method from above, and we’re good.

Screen Shot 2014-10-01 at 6.48.48 PM

Finally done, woooooo!