https://imamp.colum.edu/mediawiki/api.php?action=feedcontributions&user=Matthew.ephraim&feedformat=atomIAM MediaWiki - User contributions [en]2024-03-28T17:24:43ZUser contributionsMediaWiki 1.28.0https://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_12&diff=17934Introduction to JavaScript Fall 2010 Class 122010-12-01T00:12:11Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
In this class, you've seen how you can use JavaScript to find elements on the page, manipulate the contents of elements, hide and show elements or even add new elements. We've also made heavy use of jQuery in our JavaScript. jQuery makes is easy to do complex things with JavaScript. Unfortunately, jQuery also hides some of the underlying JavaScript code from you, so you miss out on some of the more poweful features that you can take advantage of with JavaScript.<br />
<br />
One of the things that jQuery simplifies is the '''Document Object Model''' or the '''DOM'''. Completely covering the DOM is beyond the scope of this class, but there are some things you can take advantage of right away while still using jQuery.<br />
<br />
== Your Page is a Tree ==<br />
<br />
You might not realize it, but every webpage is like a family tree. Every tag on your page has a parent and can also have children. For example, look at a simple page with a div and an unordered list:<br />
<br />
<pre><br />
<html><br />
<body><br />
<div id="container"><br />
<ul id="list"><br />
<li>Item 1</li><br />
<li>Item 2</li><br />
<li>Item 3</li><br />
</ul><br />
</div><br />
</body><br />
</html><br />
</pre><br />
<br />
This unordered list is inside of a div tag. This makes it a '''child''' of the div tag. This also makes the div tag the '''parent''' of the unordered list. Page elements that are inside of other page elements are children of the elements they are inside of. Likewise, any elements inside of a parent element are the children of that element.<br />
<br />
What about the list items inside of the unordered list element? The list items are '''children''' of the unordered list element. And the unordered list is the '''parent''' of each of the list items. Additionally, each list item is a '''sibling''' of the other list items. So, list item 1's siblings are list item 2 and list item 3.<br />
<br />
You might find it interesting that each element on the page has a parent, siblings and children, but you also might be wondering what any of this has to do with JavaScript or the Document Object Model. Among other things, the DOM is what allows you to take advantage of this family tree using JavaScript.<br />
<br />
== Traversing the DOM ==<br />
<br />
=== Parents and Children ===<br />
<br />
Let's look at that example div and unordered list again:<br />
<br />
<pre><br />
<div id="container"><br />
<ul id="list"><br />
<li>Item 1</li><br />
<li>Item 2</li><br />
<li>Item 3</li><br />
</ul><br />
</div><br />
</pre><br />
<br />
Let's say that I wanted to find the unordered list with JavaScript and then find its parent. You already know how to find the element using jQuery:<br />
<br />
var list = $("#list");<br />
<br />
But how would you find the element's parent? jQuery gives you a function called [http://api.jquery.com/parent/ '''parent'''] that allows you to find an element's parent:<br />
<br />
var listParent = $("#list").parent();<br />
<br />
The parent function returns an element that you can manipulate using jQuery just like any other element returned by jQuery.<br />
<br />
What about the list item's children? jQuery also gives you a function called [http://api.jquery.com/children/ '''children'''] that allows you to find an element's children:<br />
<br />
var listChildren = $("#list").children();<br />
<br />
This time the jQuery function returns a list of children that you can manipulate just like any other list of items returned by jQuery.<br />
<br />
=== A Useful Example ===<br />
<br />
To understand how this functionality can be useful, let's take a look at some sample HTML. In this example, we have a div with some text in it and button that says "close" on it:<br />
<br />
<pre><br />
<div><br />
<button class="close-button">Close</button><br />
This is my div<br />
</div><br />
</pre><br />
<br />
Ideally, a user will be able click on the button, which will hide the div. It would also be nice if any button that had the class "close-button" on it would hide its container div. You already know how to find the button and attach a click handler to it, but you will need to traverse the DOM to hide the element's container div. Remember that any element's container is its ''parent'', so you should be able to find and hide the button's parent using the ''parent'' function:<br />
<br />
var closeButtons = $(".close-button");<br />
closeButtons.click(function() {<br />
var parent = $(this).parent();<br />
parent.hide();<br />
});<br />
<br />
The example code above will find any elements with the "close-button" class and attach a handler that closes the parent element when the button is clicked.<br />
<br />
== Finding Siblings ==<br />
<br />
Let's change the previous example just a little bit. This time, we'll put the close button outside of the element we want to hide:<br />
<br />
<pre><br />
<body><br />
<button class="close-button">Close</button><br />
<div><br />
This is my div<br />
</div><br />
</body><br />
</pre><br />
<br />
Now, the button is outside of the div. Luckily, we can still use the DOM to find the element.<br />
<br />
Notice that the button element and the div element are both inside of the body tag. This means that the body is the parent tag of both the button and the div element. This also means that the button and the div element are siblings. In addition to finding an element's parent and children, you can also find its siblings. The [http://api.jquery.com/prev/ '''prev'''] function will find an element's nearest sibling that comes before it in the HTML (if it has one) and the [http://api.jquery.com/next/ '''next'''] function will find an element's nearest sibling that comes after it in the HTML (if it has one).<br />
<br />
In the example above, the div is the next sibling after the button. So, we can use the ''next'' function to find the div and hide it:<br />
<br />
var closeButtons = $(".close-button");<br />
closeButtons.click(function() {<br />
var div = $(this).next();<br />
div.hide();<br />
});<br />
<br />
If the div came before the button we would use the ''prev'' function instead.<br />
<br />
var closeButtons = $(".close-button");<br />
closeButtons.click(function() {<br />
var div = $(this).prev();<br />
div.hide();<br />
});<br />
<br />
Just like finding an element's parent can help to make your code more reusable, finding an element's siblings can make your code simpler and more resuable as well.<br />
<br />
== More DOM ==<br />
<br />
The Document Object Model does much more than what I've covered above. The bad news is that many of its features are fairly advanced and difficult to cover in a single class. The good news is that we've already covered many of the DOM's simpler features already. For example, being able to find an element and change its HTML or attach events to it are both features of the DOM. Being able to add new elements to the page is also a feature of he DOM that we've covered in this class.<br />
<br />
A more complete explanation of the DOM and its history can be found [http://en.wikipedia.org/wiki/Document_object_model here] and [http://www.w3.org/TR/DOM-Level-2-Core/introduction.html here].<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://www.20thingsilearned.com/home 20 Things I Learned About Browsers and the Web]<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_12&diff=17933Introduction to JavaScript Fall 2010 Class 122010-12-01T00:10:10Z<p>Matthew.ephraim: Created page with 'Back to Introduction to JavaScript Fall 2010 == Introduction == In this class, you've seen how you can use JavaScript to find elements …'</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
In this class, you've seen how you can use JavaScript to find elements on the page, manipulate the contents of elements, hide and show elements or even add new elements. We've also made heavy use of jQuery in our JavaScript. jQuery makes is easy to do complex things with JavaScript. Unfortunately, jQuery also hides some of the underlying JavaScript code from you, so you miss out on some of the more poweful features that you can take advantage of with JavaScript.<br />
<br />
One of the things that jQuery simplifies is the '''Document Object Model''' or the '''DOM'''. Completely covering the DOM is beyond the scope of this class, but there are some things you can take advantage of right away while still using jQuery.<br />
<br />
== Your Page is a Tree ==<br />
<br />
You might not realize it, but every webpage is like a family tree. Every tag on your page has a parent and can also have children. For example, look at a simple page with a div and an unordered list:<br />
<br />
<html><br />
<body><br />
<div id="container"><br />
<ul id="list"><br />
<li>Item 1</li><br />
<li>Item 2</li><br />
<li>Item 3</li><br />
</ul><br />
</div><br />
</body><br />
</html><br />
<br />
This unordered list is inside of a div tag. This makes it a '''child''' of the div tag. This also makes the div tag the '''parent''' of the unordered list. Page elements that are inside of other page elements are children of the elements they are inside of. Likewise, any elements inside of a parent element are the children of that element.<br />
<br />
What about the list items inside of the unordered list element? The list items are '''children''' of the unordered list element. And the unordered list is the '''parent''' of each of the list items. Additionally, each list item is a '''sibling''' of the other list items. So, list item 1's siblings are list item 2 and list item 3.<br />
<br />
You might find it interesting that each element on the page has a parent, siblings and children, but you also might be wondering what any of this has to do with JavaScript or the Document Object Model. Among other things, the DOM is what allows you to take advantage of this family tree using JavaScript.<br />
<br />
== Traversing the DOM ==<br />
<br />
=== Parents and Children ===<br />
<br />
Let's look at that example div and unordered list again:<br />
<br />
<div id="container"><br />
<ul id="list"><br />
<li>Item 1</li><br />
<li>Item 2</li><br />
<li>Item 3</li><br />
</ul><br />
</div><br />
<br />
Let's say that I wanted to find the unordered list with JavaScript and then find its parent. You already know how to find the element using jQuery:<br />
<br />
var list = $("#list");<br />
<br />
But how would you find the element's parent? jQuery gives you a function called [http://api.jquery.com/parent/ '''parent'''] that allows you to find an element's parent:<br />
<br />
var listParent = $("#list").parent();<br />
<br />
The parent function returns an element that you can manipulate using jQuery just like any other element returned by jQuery.<br />
<br />
What about the list item's children? jQuery also gives you a function called [http://api.jquery.com/children/ '''children'''] that allows you to find an element's children:<br />
<br />
var listChildren = $("#list").children();<br />
<br />
This time the jQuery function returns a list of children that you can manipulate just like any other list of items returned by jQuery.<br />
<br />
=== A Useful Example ===<br />
<br />
To understand how this functionality can be useful, let's take a look at some sample HTML. In this example, we have a div with some text in it and button that says "close" on it:<br />
<br />
<div><br />
<button class="close-button">Close</button><br />
This is my div<br />
</div><br />
<br />
Ideally, a user will be able click on the button, which will hide the div. It would also be nice if any button that had the class "close-button" on it would hide its container div. You already know how to find the button and attach a click handler to it, but you will need to traverse the DOM to hide the element's container div. Remember that any element's container is its ''parent'', so you should be able to find and hide the button's parent using the ''parent'' function:<br />
<br />
var closeButtons = $(".close-button");<br />
closeButtons.click(function() {<br />
var parent = $(this).parent();<br />
parent.hide();<br />
});<br />
<br />
The example code above will find any elements with the "close-button" class and attach a handler that closes the parent element when the button is clicked.<br />
<br />
== Finding Siblings ==<br />
<br />
Let's change the previous example just a little bit. This time, we'll put the close button outside of the element we want to hide:<br />
<br />
<body><br />
<button class="close-button">Close</button><br />
<div><br />
This is my div<br />
</div><br />
</body><br />
<br />
Now, the button is outside of the div. Luckily, we can still use the DOM to find the element.<br />
<br />
Notice that the button element and the div element are both inside of the body tag. This means that the body is the parent tag of both the button and the div element. This also means that the button and the div element are siblings. In addition to finding an element's parent and children, you can also find its siblings. The [http://api.jquery.com/prev/ '''prev'''] function will find an element's nearest sibling that comes before it in the HTML (if it has one) and the [http://api.jquery.com/next/ '''next'''] function will find an element's nearest sibling that comes after it in the HTML (if it has one).<br />
<br />
In the example above, the div is the next sibling after the button. So, we can use the ''next'' function to find the div and hide it:<br />
<br />
var closeButtons = $(".close-button");<br />
closeButtons.click(function() {<br />
var div = $(this).next();<br />
div.hide();<br />
});<br />
<br />
If the div came before the button we would use the ''prev'' function instead.<br />
<br />
var closeButtons = $(".close-button");<br />
closeButtons.click(function() {<br />
var div = $(this).prev();<br />
div.hide();<br />
});<br />
<br />
Just like finding an element's parent can help to make your code more reusable, finding an element's siblings can make your code simpler and more resuable as well.<br />
<br />
== More DOM ==<br />
<br />
The Document Object Model does much more than what I've covered above. The bad news is that many of its features are fairly advanced and difficult to cover in a single class. The good news is that we've already covered many of the DOM's simpler features already. For example, being able to find an element and change its HTML or attach events to it are both features of the DOM. Being able to add new elements to the page is also a feature of he DOM that we've covered in this class.<br />
<br />
A more complete explanation of the DOM and its history can be found [http://en.wikipedia.org/wiki/Document_object_model here] and [http://www.w3.org/TR/DOM-Level-2-Core/introduction.html here].<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://www.20thingsilearned.com/home 20 Things I Learned About Browsers and the Web]<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17932Introduction to JavaScript Fall 20102010-12-01T00:09:53Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* Class 9 (11/2/2010): [[Introduction_to_JavaScript_Fall_2010_Class_9|Raphaël]]<br />
* Class 10 (11/9/2010): [[Introduction_to_JavaScript_Fall_2010_Class_10|Timers]]<br />
* Class 11 (11/16/2010): [[Introduction_to_JavaScript_Fall_2010_Class_11|Ajax]]<br />
* Class 12 (11/30/2010): [[Introduction_to_JavaScript_Fall_2010_Class_12|The DOM]]<br />
<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_11&diff=17931Introduction to JavaScript Fall 2010 Class 112010-12-01T00:08:38Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
If you paid any attention the web development world in the last 5 years, you may have noticed that the term "Ajax" was one of the hottest buzzwords. While some of the buzz was overstated, Ajax does allow you to do some very useful things with JavaScript. This week, you'll see how you can use jQuery and Ajax to make your webpages more dynamic. However, to understand Ajax, you will first need to undertand how the process of requesting and receiving webpage works.<br />
<br />
== Client/Server ==<br />
<br />
Opening a new webpage in your browser may seem like a pretty easy process. You type in the address, hit enter, and the page loads. However, sending a webpage to your computer is not as simple as it seems. Behind the scenes, your computer is formatting a '''request'''. That request is sent out over the Internet and eventually received by another computer. The computer that receives the request must then construct a response to send back to your computer. In the case of a webpage, that response may be some HTML that represents the webpage you requested. The response could also be an image, a JavaScript file or possibly some XML.<br />
<br />
For this class, I'll ignore most of the things that happen along the way as a request is sent over the Internet and a response is returned. However, two key elements you'll need to understand when working with Ajax are the '''client''' and the '''server'''.<br />
<br />
=== The Client ===<br />
<br />
In short, the tool that you use to make a request over the Internet is known as the '''client'''. In this class, our client has been a web browser. We've mainly used Mozilla Firefox, so Firefox has been our client. Safari, Chrome, and Internet Explorer are also clients. Chat programs, Twitter clients and email programs are all clients as well. Any program that makes a request over the Internet can be considered a client.<br />
<br />
Ajax is a browser specific technology, so I'll focus mainly on web browsers as clients.<br />
<br />
=== The Server ===<br />
<br />
When a browser requests a webpage, it will ideally receive response back. The program that responds to the message by sending a webpage back is known as the '''server'''. While the term "server" can refer to an actual computer, in this case I'll use "server" to mean a piece of software running on a computer. Just like a web browser is a program that sends and receives messages over the Internet, a server is also a program that sends and receives messages over the Internet.<br />
<br />
There are many types of servers, but one specific type of server is called a '''web server'''. A web server is a program that is mainly designed to respond to requests for webpages. Web servers are especially good at talking to clients that are requesting HTML, images, JavaScript files or any other files related to webpages. Additionally, web servers can handle requests for webpages that are built dynamically using languages like PHP, Python, or Ruby.<br />
<br />
== The Request Response Cycle ==<br />
<br />
As you've seen above, any request for a webpage involves sending a '''request''' from a web browser '''(the client)''' to a remote computer. The remote computer will be running a special program '''(the server)''' that knows how to handle the request and returns a '''response''' back to the computer with the web browser running on it. This roundtrip path from the client to the server and back again is known as the '''request response cycle'''.<br />
<br />
At first glance, it might seem like a simple request for a webpage would involve only one roundtrip of the request response cycle. And, indeed, if you use your browser to request a simple webpage with only text on it the web server will respond with an HTML file, making one complete round of the request response cycle.<br />
<br />
However, if instead of being a text only webpage, the page also had one image on it, the client would need to request the HTML file ''and'' the image file. The server would also need to respond with the HTML file ''and'' the image file. In most cases, the web server can only respond with one type of file at a time, and the web browser can only handle one type of response at a time. Which means that the browser needs to request the HTML file and the image file separately and the server needs to respond with the HTML file and the image file separately. Therefore, requesting a webpage with one image on it would involve two complete round trips of the request response cycle, one trip for the HTML and one trip for the image.<br />
<br />
For every other file you add to the webpage, whether it's an image, a stylesheet or a JavaScript file, the request for the webpage will involve another request response cycle. The more complicated a webpage gets, the more requests and responses there will be. While the number of requests and responses might seem like only a technical detail there's an important reason to pay attention to how many requests a page needs to make.<br />
<br />
=== Response Time ===<br />
<br />
As you've probably noticed, webpages don't always load quickly in your browser. Some pages load almost instantly (think about the [http://www.google.com Google] homepage). Other pages can take a long time to load. If a page takes long enough to load you may even give up and go somewhere else. The amount of time it takes for all the associated files for a webpage (the HTML, the css, the images, etc) is the '''response time''' for the webpage. When the browser requests a single image or a JavaScript file, the amount of time it takes for that single file to load is also called the '''response time'''. Essentially, the longer the response time, the longer is a user is going to have to wait before they can use your webpage.<br />
<br />
For individual webpages, the response time will be dependent on how long it takes to load everything that the webpage depends on. A user might be willing to wait 1 second or more for a single webpage to load. However, most sites have multiple pages. Often, they will include forms that allow users to search the site or enter new information. If the response time for each individual page is too long user can quickly become frustrated and may leave the website altogether.<br />
<br />
Wouldn't it be nice if you could update a webpage without having to reload everything?<br />
<br />
== Ajax ==<br />
<br />
In this class you've learned how to use JavaScript to handle user events, to change a page's HTML, and to read the values that a user entered into a form. Taken together, you've got most of what you need to update a webpage without having to reload it. The one thing you dont have yet is the ability to use the ''client'' (the browser) to request more information from the ''server'' without having to reload the page. This is where '''Ajax''' comes in handy.<br />
<br />
=== A Short History ===<br />
<br />
Early browsers had very few built in options for requesting information from the server without reloading the page. Various workarounds were developed for getting around this problem, but it wasn't until the late 1990s that a straightforward solution was developed. In 1999, Microsoft added the ability to make an ''"XMLHTTP request"'' to ''Internet Explorer''. In a nutshell, an XMLHTTP request allowed JavaScript to ask for additional information (formatted as XML) from the server without reloading the page. While XMLHTTP request made it easier to write JavaSript that made requests to the server, other browsers didn't immediately add similar functionality. So, any webpages that used XMLHTTP request would only work in Internet Explorer.<br />
<br />
Fortunately, by 2005, other popular browsers, like Mozilla Firefox, had added functionality that replicated Internet Explorer's XMLHTTP request. Around the same time, sites like [http://mail.google.com Gmail] and [http://maps.google.com Google Maps] were released and relied heavily on JavaScript and XMLHTTP request. User experience designer Jesse James Garret coined the acronym '''AJAX''' (Asynchronous JavaScript and XML) to descibe the phenomenon of these new JavaScript heavy sites.<br />
<br />
Today, every popular browser has added XMLHTTP request functionality. As people have developed sites that use JavaScript to request not only XML from the server, but also data in other formats (like ''JSON''), the ''X'' part of the ''AJAX'' acronym has become inaccurate, and the acronym '''AJAX''' has changed to the broader term '''Ajax'''.<br />
<br />
=== Using Ajax ===<br />
<br />
Because Ajax functionality wasn't immediately added to all browsers, building a website that takes advantage of Ajax across all browsers isn't necessarily as straightforward as you might expect. In particular, older versions of Internet Explorer use a form of Ajax that is very different than most modern browsers, including more recent versions of Internet Explorer. It's possible to write your own Ajax JavaScript that works in all browsers, but, in general, it will be much faster and less error prone to choose a JavaScript library that supports Ajax.<br />
<br />
Fortunately, the library that we've been using in class, jQuery, has support for Ajax. You can find extensive documentation on jQuery's Ajax functionality [http://api.jquery.com/category/ajax/ here].<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://www.newsweek.com/2010/11/15/career-tree.html Newsweek's Career Tree (using Raphael)]<br />
<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_11&diff=17930Introduction to JavaScript Fall 2010 Class 112010-12-01T00:07:46Z<p>Matthew.ephraim: Created page with 'Back to Introduction to JavaScript Fall 2010 == Introduction == If you paid any attention the web development world in the last 5 years…'</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
If you paid any attention the web development world in the last 5 years, you may have noticed that the term "Ajax" was one of the hottest buzzwords. While some of the buzz was overstated, Ajax does allow you to do some very useful things with JavaScript. This week, you'll see how you can use jQuery and Ajax to make your webpages more dynamic. However, to understand Ajax, you will first need to undertand how the process of requesting and receiving webpage works.<br />
<br />
== Client/Server ==<br />
<br />
Opening a new webpage in your browser may seem like a pretty easy process. You type in the address, hit enter, and the page loads. However, sending a webpage to your computer is not as simple as it seems. Behind the scenes, your computer is formatting a '''request'''. That request is sent out over the Internet and eventually received by another computer. The computer that receives the request must then construct a response to send back to your computer. In the case of a webpage, that response may be some HTML that represents the webpage you requested. The response could also be an image, a JavaScript file or possibly some XML.<br />
<br />
For this class, I'll ignore most of the things that happen along the way as a request is sent over the Internet and a response is returned. However, two key elements you'll need to understand when working with Ajax are the '''client''' and the '''server'''.<br />
<br />
=== The Client ===<br />
<br />
In short, the tool that you use to make a request over the Internet is known as the '''client'''. In this class, our client has been a web browser. We've mainly used Mozilla Firefox, so Firefox has been our client. Safari, Chrome, and Internet Explorer are also clients. Chat programs, Twitter clients and email programs are all clients as well. Any program that makes a request over the Internet can be considered a client.<br />
<br />
Ajax is a browser specific technology, so I'll focus mainly on web browsers as clients.<br />
<br />
=== The Server ===<br />
<br />
When a browser requests a webpage, it will ideally receive response back. The program that responds to the message by sending a webpage back is known as the '''server'''. While the term "server" can refer to an actual computer, in this case I'll use "server" to mean a piece of software running on a computer. Just like a web browser is a program that sends and receives messages over the Internet, a server is also a program that sends and receives messages over the Internet.<br />
<br />
There are many types of servers, but one specific type of server is called a '''web server'''. A web server is a program that is mainly designed to respond to requests for webpages. Web servers are especially good at talking to clients that are requesting HTML, images, JavaScript files or any other files related to webpages. Additionally, web servers can handle requests for webpages that are built dynamically using languages like PHP, Python, or Ruby.<br />
<br />
== The Request Response Cycle ==<br />
<br />
As you've seen above, any request for a webpage involves sending a '''request''' from a web browser '''(the client)''' to a remote computer. The remote computer will be running a special program '''(the server)''' that knows how to handle the request and returns a '''response''' back to the computer with the web browser running on it. This roundtrip path from the client to the server and back again is known as the '''request response cycle'''.<br />
<br />
At first glance, it might seem like a simple request for a webpage would involve only one roundtrip of the request response cycle. And, indeed, if you use your browser to request a simple webpage with only text on it the web server will respond with an HTML file, making one complete round of the request response cycle.<br />
<br />
However, if instead of being a text only webpage, the page also had one image on it, the client would need to request the HTML file ''and'' the image file. The server would also need to respond with the HTML file ''and'' the image file. In most cases, the web server can only respond with one type of file at a time, and the web browser can only handle one type of response at a time. Which means that the browser needs to request the HTML file and the image file separately and the server needs to respond with the HTML file and the image file separately. Therefore, requesting a webpage with one image on it would involve two complete round trips of the request response cycle, one trip for the HTML and one trip for the image.<br />
<br />
For every other file you add to the webpage, whether it's an image, a stylesheet or a JavaScript file, the request for the webpage will involve another request response cycle. The more complicated a webpage gets, the more requests and responses there will be. While the number of requests and responses might seem like only a technical detail there's an important reason to pay attention to how many requests a page needs to make.<br />
<br />
=== Response Time ===<br />
<br />
As you've probably noticed, webpages don't always load quickly in your browser. Some pages load almost instantly (think about the [http://www.google.com Google] homepage). Other pages can take a long time to load. If a page takes long enough to load you may even give up and go somewhere else. The amount of time it takes for all the associated files for a webpage (the HTML, the css, the images, etc) is the '''response time''' for the webpage. When the browser requests a single image or a JavaScript file, the amount of time it takes for that single file to load is also called the '''response time'''. Essentially, the longer the response time, the longer is a user is going to have to wait before they can use your webpage.<br />
<br />
For individual webpages, the response time will be dependent on how long it takes to load everything that the webpage depends on. A user might be willing to wait 1 second or more for a single webpage to load. However, most sites have multiple pages. Often, they will include forms that allow users to search the site or enter new information. If the response time for each individual page is too long user can quickly become frustrated and may leave the website altogether.<br />
<br />
Wouldn't it be nice if you could update a webpage without having to reload everything?<br />
<br />
== Ajax ==<br />
<br />
In this class you've learned how to use JavaScript to handle user events, to change a page's HTML, and to read the values that a user entered into a form. Taken together, you've got most of what you need to update a webpage without having to reload it. The one thing you dont have yet is the ability to use the ''client'' (the browser) to request more information from the ''server'' without having to reload the page. This is where '''Ajax''' comes in handy.<br />
<br />
=== A Short History ===<br />
<br />
Early browsers had very few built in options for requesting information from the server without reloading the page. Various workarounds were developed for getting around this problem, but it wasn't until the late 1990s that a straightforward solution was developed. In 1999, Microsoft added the ability to make an ''"XMLHTTP request"'' to ''Internet Explorer''. In a nutshell, an XMLHTTP request allowed JavaScript to ask for additional information (formatted as XML) from the server without reloading the page. While XMLHTTP request made it easier to write JavaSript that made requests to the server, other browsers didn't immediately add similar functionality. So, any webpages that used XMLHTTP request would only work in Internet Explorer.<br />
<br />
Fortunately, by 2005, other popular browsers, like Mozilla Firefox, had added functionality that replicated Internet Explorer's XMLHTTP request. Around the same time, sites like [http://mail.google.com Gmail] and [http://maps.google.com Google Maps] were released and relied heavily on JavaScript and XMLHTTP request. User experience designer Jesse James Garret coined the acronym '''AJAX''' (Asynchronous JavaScript and XML) to descibe the phenomenon of these new JavaScript heavy sites.<br />
<br />
Today, every popular browser has added XMLHTTP request functionality. As people have developed sites that use JavaScript to request not only XML from the server, but also data in other formats (like ''JSON''), the ''X'' part of the ''AJAX'' acronym has become inaccurate, and the acronym '''AJAX''' has changed to the broader term '''Ajax'''.<br />
<br />
=== Using Ajax ===<br />
<br />
Because Ajax functionality wasn't immediately added to all browsers, building a website that takes advantage of Ajax across all browsers isn't necessarily as straightforward as you might expect. In particular, older versions of Internet Explorer use a form of Ajax that is very different than most modern browsers, including more recent versions of Internet Explorer. It's possible to write your own Ajax JavaScript that works in all browsers, but, in general, it will be much faster and less error prone to choose a JavaScript library that supports Ajax.<br />
<br />
Fortunately, the library that we've been using in class, jQuery, has support for Ajax. You can find extensive documentation on jQuery's Ajax functionality [here http://api.jquery.com/category/ajax/].<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://www.newsweek.com/2010/11/15/career-tree.html Newsweek's Career Tree (using Raphael)]<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17887Introduction to JavaScript Fall 20102010-11-10T00:22:57Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* Class 9 (11/2/2010): [[Introduction_to_JavaScript_Fall_2010_Class_9|Raphaël]]<br />
* Class 10 (11/9/2010): [[Introduction_to_JavaScript_Fall_2010_Class_10|Timers]]<br />
<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_10&diff=17886Introduction to JavaScript Fall 2010 Class 102010-11-10T00:21:43Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss '''anonymous functions''', which will be useful when we start using timers.<br />
<br />
== Anonymous Functions ==<br />
<br />
'''Anonymous functions''' are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:<br />
<br />
function() {<br />
// your code here<br />
}<br />
<br />
Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:<br />
<br />
Behavior.someFunction = '''function() {<br />
// your code here<br />
};'''<br />
<br />
Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass<br />
an anonymous function as a parameter to the jQuery ''click'' function:<br />
<br />
$("#button-id").click(function() {<br />
// code for handling the click event<br />
});<br />
<br />
The anonymous function will work exactly the same way this code:<br />
<br />
$("#button-id").click(handleClick);<br />
<br />
function handleClick() {<br />
// code for handling the click event<br />
}<br />
<br />
The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in<br />
to the click function.<br />
<br />
Anonymous functions will become more useful when we start working with timers.<br />
<br />
== JavaScript Timers ==<br />
<br />
Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay.<br />
Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.<br />
<br />
=== Using a Timer to Delay a Function Call ===<br />
<br />
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:<br />
<br />
$('#button-id').click(addParagraph);<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
You should already be familiar with this kind of thing, because we've done it in class.<br />
<br />
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.<br />
<br />
// When the button is clicked, create a new timer that will call the<br />
// addParagraph function after 2 seconds<br />
$('#button-id').click(function) {<br />
'''setTimeout(addParagraph, 2000);'''<br />
};<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:<br />
<br />
// Call '''functionName''' after 1 second<br />
setTimeout('''functionName''', 1000);<br />
<br />
Or it will take in an anonymous function that you want to be called:<br />
<br />
// Call the function block after 1 second<br />
setTimeout('''function() {'''<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).<br />
<br />
=== Using a Timer to Repeatedly Call a Function ===<br />
<br />
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:<br />
<br />
// Call '''myFunction''' every second<br />
setInterval('''myFunction''', 1000);<br />
<br />
Or:<br />
<br />
// Call the function block every second<br />
setInterval('''function() {<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.<br />
<br />
== Stopping Timers ==<br />
<br />
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?<br />
<br />
=== Stopping setTimeout ===<br />
<br />
When you call the '''setTimeout''' function it returns a value you can store in a variable:<br />
<br />
var timer = setTimeout(functionName, 1000);<br />
<br />
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.<br />
<br />
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:<br />
<br />
// Create a new timer and store it in the ''timer'' variable<br />
var timer = setTimeout(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// If 10 seconds haven't passed already this will cancel the timer<br />
// and the function will never get called<br />
clearTimeout(timer);<br />
<br />
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.<br />
<br />
=== Stopping setInterval ===<br />
<br />
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:<br />
<br />
var timer = setInterval(functionName, 1000);<br />
<br />
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:<br />
<br />
// Create a new timer and store it in the '''timer''' variable<br />
var timer = setInterval(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// Stop the timer from running. This will prevent the<br />
// timer from calling the function again<br />
clearInterval(timer);<br />
<br />
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://processingjs.org/exhibition Processing.js]<br />
<br />
== Activity ==<br />
<br />
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.<br />
<br />
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter.zip here].<br />
<br />
<!--<br />
The completed version is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter_complete.zip here].<br />
--><br />
<br />
== Assignment 5 ==<br />
<br />
'''Due Friday November 19th'''<br />
<br />
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:<br />
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''<br />
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.<br />
* Draw as many elements as you want, but draw at least 3 elements.<br />
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.<br />
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.<br />
<br />
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'x' and 'y' (or 'cx' and 'cy' for circles) with the '''attr''' <br />
or '''animation''' functions:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// animate the circle to position x = 20, and y = 30<br />
circle.animate({ cx: 20, cy: 30 }, 200);<br />
<br />
var rect = canvas.circle(100, 100, 10, 10);<br />
<br />
// animate the rect to position x = 50, and y = 20<br />
circle.animate({ x: 50, y: 20 }, 500);<br />
<br />
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].<br />
<br />
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// change the color of the element when the user clicks on it<br />
circle.click(function() {<br />
circle.animate({ fill: '#6DBE9F' });<br />
});<br />
<br />
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2010_Class_10|Raphaël]] page from last week to see how to draw Raphaël elements.<br />
<br />
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.<br />
<br />
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/circles.zip here]. You can use it as a starting point if you'd like.<br />
<br />
If you have any questions about the assignment let me know.<br />
<br />
== Final Project ==<br />
<br />
We've covered a lot of topics in the class. I'd like you to create final project<br />
that incorporates '''at least 4''' of the topics listed below.<br />
<br />
'''The project is up to you'''. If you have a project for '''another class''' or something at '''work'''<br />
that could be made better using JavaScript, you are welcome to use it. If you have a '''personal<br />
portfolio''' that you'd like to make more exciting with JavaScript, that works too. You can also<br />
create a simple '''art''' project or '''game'''.<br />
<br />
I'd like you to email your project idea before next week's class. If you are having a hard time<br />
coming up with a project, let me know and I can help you figure out something else.<br />
<br />
The import thing is: '''don't panic'''. I'm not expecting anyone to become a JavaScript genius<br />
in this class. Your project can be simple. Just make sure to include '''at least 4''' of the topics<br />
listed below.<br />
<br />
Your final project will be '''due Friday December 10th''', and you will present your project in class<br />
on '''December 13th'''.<br />
<br />
'''Topics From This Class'''<br />
<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_3|if and else (control flow)]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_3|Loops]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery event handling]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|Changing styles]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Objects]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Storing your code with objects]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_7|Reading forms]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_9|JavaScript art with Raphaël]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_10|Timers]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_10&diff=17885Introduction to JavaScript Fall 2010 Class 102010-11-10T00:20:00Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss '''anonymous functions''', which will be useful when we start using timers.<br />
<br />
== Anonymous Functions ==<br />
<br />
'''Anonymous functions''' are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:<br />
<br />
function() {<br />
// your code here<br />
}<br />
<br />
Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:<br />
<br />
Behavior.someFunction = '''function() {<br />
// your code here<br />
};'''<br />
<br />
Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass<br />
an anonymous function as a parameter to the jQuery ''click'' function:<br />
<br />
$("#button-id").click(function() {<br />
// code for handling the click event<br />
});<br />
<br />
The anonymous function will work exactly the same way this code:<br />
<br />
$("#button-id").click(handleClick);<br />
<br />
function handleClick() {<br />
// code for handling the click event<br />
}<br />
<br />
The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in<br />
to the click function.<br />
<br />
Anonymous functions will become more useful when we start working with timers.<br />
<br />
== JavaScript Timers ==<br />
<br />
Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay.<br />
Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.<br />
<br />
=== Using a Timer to Delay a Function Call ===<br />
<br />
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:<br />
<br />
$('#button-id').click(addParagraph);<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
You should already be familiar with this kind of thing, because we've done it in class.<br />
<br />
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.<br />
<br />
// When the button is clicked, create a new timer that will call the<br />
// addParagraph function after 2 seconds<br />
$('#button-id').click(function) {<br />
'''setTimeout(addParagraph, 2000);'''<br />
};<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:<br />
<br />
// Call '''functionName''' after 1 second<br />
setTimeout('''functionName''', 1000);<br />
<br />
Or it will take in an anonymous function that you want to be called:<br />
<br />
// Call the function block after 1 second<br />
setTimeout('''function() {'''<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).<br />
<br />
=== Using a Timer to Repeatedly Call a Function ===<br />
<br />
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:<br />
<br />
// Call '''myFunction''' every second<br />
setInterval('''myFunction''', 1000);<br />
<br />
Or:<br />
<br />
// Call the function block every second<br />
setInterval('''function() {<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.<br />
<br />
== Stopping Timers ==<br />
<br />
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?<br />
<br />
=== Stopping setTimeout ===<br />
<br />
When you call the '''setTimeout''' function it returns a value you can store in a variable:<br />
<br />
var timer = setTimeout(functionName, 1000);<br />
<br />
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.<br />
<br />
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:<br />
<br />
// Create a new timer and store it in the ''timer'' variable<br />
var timer = setTimeout(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// If 10 seconds haven't passed already this will cancel the timer<br />
// and the function will never get called<br />
clearTimeout(timer);<br />
<br />
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.<br />
<br />
=== Stopping setInterval ===<br />
<br />
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:<br />
<br />
var timer = setInterval(functionName, 1000);<br />
<br />
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:<br />
<br />
// Create a new timer and store it in the '''timer''' variable<br />
var timer = setInterval(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// Stop the timer from running. This will prevent the<br />
// timer from calling the function again<br />
clearInterval(timer);<br />
<br />
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://processingjs.org/exhibition Processing.js]<br />
<br />
== Activity ==<br />
<br />
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.<br />
<br />
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter.zip here].<br />
<br />
<!--<br />
The completed version is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter_complete.zip here].<br />
--><br />
<br />
== Assignment 5 ==<br />
<br />
'''Due Friday November 19th'''<br />
<br />
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:<br />
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''<br />
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.<br />
* Draw as many elements as you want, but draw at least 3 elements.<br />
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.<br />
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.<br />
<br />
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'x' and 'y' (or 'cx' and 'cy' for circles) with the '''attr''' <br />
or '''animation''' functions:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// animate the circle to position x = 20, and y = 30<br />
circle.animate({ cx: 20, cy: 30 }, 200);<br />
<br />
var rect = canvas.circle(100, 100, 10, 10);<br />
<br />
// animate the rect to position x = 50, and y = 20<br />
circle.animate({ x: 50, y: 20 }, 500);<br />
<br />
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].<br />
<br />
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// change the color of the element when the user clicks on it<br />
circle.click(function() {<br />
circle.animate({ fill: '#6DBE9F' });<br />
});<br />
<br />
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2010_Class_10|Raphaël]] page from last week to see how to draw Raphaël elements.<br />
<br />
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.<br />
<br />
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/circles.zip here]. You can use it as a starting point if you'd like.<br />
<br />
If you have any questions about the assignment let me know.<br />
<br />
== Final Project ==<br />
<br />
We've covered a lot of topics in the class. I'd like you to create final project<br />
that incorporates '''at least 4''' of the topics listed below.<br />
<br />
'''The project is up to you'''. If you have a project for '''another class''' or something at '''work'''<br />
that could be made better using JavaScript, you are welcome to use it. If you have a '''personal<br />
portfolio''' that you'd like to make more exciting with JavaScript, that works too. You can also<br />
create a simple '''art''' project or '''game'''.<br />
<br />
I'd like you to email your project idea before next week's class. If you are having a hard time<br />
coming up with a project, let me know and I can help you figure out something else.<br />
<br />
The import thing is: '''don't panic'''. I'm not expecting anyone to become a JavaScript genius<br />
in this class. Your project can be simple. Just make sure to include '''at least 4''' of the topics<br />
listed below.<br />
<br />
Your final project will be due Friday December 10th, and you will present your project in class<br />
on December 13th.<br />
<br />
'''Topics From This Class'''<br />
<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_3|if and else (control flow)]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_3|Loops]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery event handling]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|Changing styles]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Objects]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Storing your code with objects]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_7|Reading forms]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_9|JavaScript art with Raphaël]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_10|Timers]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17884Introduction to JavaScript Fall 20102010-11-10T00:19:35Z<p>Matthew.ephraim: Undo revision 17883 by Matthew.ephraim (Talk)</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* Class 9 (11/2/2010): [[Introduction_to_JavaScript_Fall_2010_Class_9|Raphaël]]<br />
<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17883Introduction to JavaScript Fall 20102010-11-10T00:17:23Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss '''anonymous functions''', which will be useful when we start using timers.<br />
<br />
== Anonymous Functions ==<br />
<br />
'''Anonymous functions''' are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:<br />
<br />
function() {<br />
// your code here<br />
}<br />
<br />
Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:<br />
<br />
Behavior.someFunction = '''function() {<br />
// your code here<br />
};'''<br />
<br />
Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass<br />
an anonymous function as a parameter to the jQuery ''click'' function:<br />
<br />
$("#button-id").click(function() {<br />
// code for handling the click event<br />
});<br />
<br />
The anonymous function will work exactly the same way this code:<br />
<br />
$("#button-id").click(handleClick);<br />
<br />
function handleClick() {<br />
// code for handling the click event<br />
}<br />
<br />
The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in<br />
to the click function.<br />
<br />
Anonymous functions will become more useful when we start working with timers.<br />
<br />
== JavaScript Timers ==<br />
<br />
Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay.<br />
Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.<br />
<br />
=== Using a Timer to Delay a Function Call ===<br />
<br />
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:<br />
<br />
$('#button-id').click(addParagraph);<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
You should already be familiar with this kind of thing, because we've done it in class.<br />
<br />
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.<br />
<br />
// When the button is clicked, create a new timer that will call the<br />
// addParagraph function after 2 seconds<br />
$('#button-id').click(function) {<br />
'''setTimeout(addParagraph, 2000);'''<br />
};<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:<br />
<br />
// Call '''functionName''' after 1 second<br />
setTimeout('''functionName''', 1000);<br />
<br />
Or it will take in an anonymous function that you want to be called:<br />
<br />
// Call the function block after 1 second<br />
setTimeout('''function() {'''<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).<br />
<br />
=== Using a Timer to Repeatedly Call a Function ===<br />
<br />
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:<br />
<br />
// Call '''myFunction''' every second<br />
setInterval('''myFunction''', 1000);<br />
<br />
Or:<br />
<br />
// Call the function block every second<br />
setInterval('''function() {<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.<br />
<br />
== Stopping Timers ==<br />
<br />
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?<br />
<br />
=== Stopping setTimeout ===<br />
<br />
When you call the '''setTimeout''' function it returns a value you can store in a variable:<br />
<br />
var timer = setTimeout(functionName, 1000);<br />
<br />
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.<br />
<br />
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:<br />
<br />
// Create a new timer and store it in the ''timer'' variable<br />
var timer = setTimeout(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// If 10 seconds haven't passed already this will cancel the timer<br />
// and the function will never get called<br />
clearTimeout(timer);<br />
<br />
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.<br />
<br />
=== Stopping setInterval ===<br />
<br />
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:<br />
<br />
var timer = setInterval(functionName, 1000);<br />
<br />
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:<br />
<br />
// Create a new timer and store it in the '''timer''' variable<br />
var timer = setInterval(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// Stop the timer from running. This will prevent the<br />
// timer from calling the function again<br />
clearInterval(timer);<br />
<br />
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.<br />
<br />
== Activity ==<br />
<br />
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.<br />
<br />
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter.zip here].<br />
<br />
<!--<br />
The completed version is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter_complete.zip here].<br />
--><br />
<br />
== Assignment 5 ==<br />
<br />
'''Due Friday November 19th'''<br />
<br />
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:<br />
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''<br />
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.<br />
* Draw as many elements as you want, but draw at least 3 elements.<br />
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.<br />
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.<br />
<br />
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'x' and 'y' (or 'cx' and 'cy' for circles) with the '''attr''' <br />
or '''animation''' functions:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// animate the circle to position x = 20, and y = 30<br />
circle.animate({ cx: 20, cy: 30 }, 200);<br />
<br />
var rect = canvas.circle(100, 100, 10, 10);<br />
<br />
// animate the rect to position x = 50, and y = 20<br />
circle.animate({ x: 50, y: 20 }, 500);<br />
<br />
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].<br />
<br />
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// change the color of the element when the user clicks on it<br />
circle.click(function() {<br />
circle.animate({ fill: '#6DBE9F' });<br />
});<br />
<br />
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2010_Class_10|Raphaël]] page from last week to see how to draw Raphaël elements.<br />
<br />
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.<br />
<br />
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/circles.zip here]. You can use it as a starting point if you'd like.<br />
<br />
If you have any questions about the assignment let me know.<br />
<br />
== Final Project ==<br />
<br />
We've covered a lot of topics in the class. I'd like you to create final project<br />
that incorporates '''at least 4''' of the topics listed below.<br />
<br />
'''The project is up to you'''. If you have a project for '''another class''' or something at '''work'''<br />
that could be made better using JavaScript, you are welcome to use it. If you have a '''personal<br />
portfolio''' that you'd like to make more exciting with JavaScript, that works too. You can also<br />
create a simple '''art''' project or '''game'''.<br />
<br />
I'd like you to email your project idea before next week's class. If you are having a hard time<br />
coming up with a project, let me know and I can help you figure out something else.<br />
<br />
The import thing is: '''don't panic'''. I'm not expecting anyone to become a JavaScript genius<br />
in this class. Your project can be simple. Just make sure to include '''at least 4''' of the topics<br />
listed below.<br />
<br />
Your final project will be due Friday December 10th, and you will present your project in class<br />
on December 13th.<br />
<br />
'''Topics'''<br />
<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_3|if and else (control flow)]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_3|Loops]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|jQuery event handling]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_5|Changing styles]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Objects]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_6|Storing your code with objects]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_7|Reading forms]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_9|JavaScript art with Raphaël]]<br />
* [[Introduction_to_JavaScript_Fall_2010_Class_10|Timers]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_10&diff=17882Introduction to JavaScript Fall 2010 Class 102010-11-09T22:34:40Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss '''anonymous functions''', which will be useful when we start using timers.<br />
<br />
== Anonymous Functions ==<br />
<br />
'''Anonymous functions''' are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:<br />
<br />
function() {<br />
// your code here<br />
}<br />
<br />
Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:<br />
<br />
Behavior.someFunction = '''function() {<br />
// your code here<br />
};'''<br />
<br />
Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass<br />
an anonymous function as a parameter to the jQuery ''click'' function:<br />
<br />
$("#button-id").click(function() {<br />
// code for handling the click event<br />
});<br />
<br />
The anonymous function will work exactly the same way this code:<br />
<br />
$("#button-id").click(handleClick);<br />
<br />
function handleClick() {<br />
// code for handling the click event<br />
}<br />
<br />
The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in<br />
to the click function.<br />
<br />
Anonymous functions will become more useful when we start working with timers.<br />
<br />
== JavaScript Timers ==<br />
<br />
Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay.<br />
Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.<br />
<br />
=== Using a Timer to Delay a Function Call ===<br />
<br />
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:<br />
<br />
$('#button-id').click(addParagraph);<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
You should already be familiar with this kind of thing, because we've done it in class.<br />
<br />
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.<br />
<br />
// When the button is clicked, create a new timer that will call the<br />
// addParagraph function after 2 seconds<br />
$('#button-id').click(function) {<br />
'''setTimeout(addParagraph, 2000);'''<br />
};<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:<br />
<br />
// Call '''functionName''' after 1 second<br />
setTimeout('''functionName''', 1000);<br />
<br />
Or it will take in an anonymous function that you want to be called:<br />
<br />
// Call the function block after 1 second<br />
setTimeout('''function() {'''<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).<br />
<br />
=== Using a Timer to Repeatedly Call a Function ===<br />
<br />
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:<br />
<br />
// Call '''myFunction''' every second<br />
setInterval('''myFunction''', 1000);<br />
<br />
Or:<br />
<br />
// Call the function block every second<br />
setInterval('''function() {<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.<br />
<br />
== Stopping Timers ==<br />
<br />
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?<br />
<br />
=== Stopping setTimeout ===<br />
<br />
When you call the '''setTimeout''' function it returns a value you can store in a variable:<br />
<br />
var timer = setTimeout(functionName, 1000);<br />
<br />
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.<br />
<br />
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:<br />
<br />
// Create a new timer and store it in the ''timer'' variable<br />
var timer = setTimeout(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// If 10 seconds haven't passed already this will cancel the timer<br />
// and the function will never get called<br />
clearTimeout(timer);<br />
<br />
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.<br />
<br />
=== Stopping setInterval ===<br />
<br />
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:<br />
<br />
var timer = setInterval(functionName, 1000);<br />
<br />
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:<br />
<br />
// Create a new timer and store it in the '''timer''' variable<br />
var timer = setInterval(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// Stop the timer from running. This will prevent the<br />
// timer from calling the function again<br />
clearInterval(timer);<br />
<br />
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.<br />
<br />
== Activity ==<br />
<br />
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.<br />
<br />
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter.zip here].<br />
<br />
<!--<br />
The completed version is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter_complete.zip here].<br />
--><br />
<br />
== Assignment 5 ==<br />
<br />
'''Due Friday November 19th'''<br />
<br />
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:<br />
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''<br />
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.<br />
* Draw as many elements as you want, but draw at least 3 elements.<br />
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.<br />
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.<br />
<br />
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'x' and 'y' (or 'cx' and 'cy' for circles) with the '''attr''' <br />
or '''animation''' functions:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// animate the circle to position x = 20, and y = 30<br />
circle.animate({ cx: 20, cy: 30 }, 200);<br />
<br />
var rect = canvas.circle(100, 100, 10, 10);<br />
<br />
// animate the rect to position x = 50, and y = 20<br />
circle.animate({ x: 50, y: 20 }, 500);<br />
<br />
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].<br />
<br />
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// change the color of the element when the user clicks on it<br />
circle.click(function() {<br />
circle.animate({ fill: '#6DBE9F' });<br />
});<br />
<br />
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2010_Class_10|Raphaël]] page from last week to see how to draw Raphaël elements.<br />
<br />
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.<br />
<br />
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/circles.zip here]. You can use it as a starting point if you'd like.<br />
<br />
If you have any questions about the assignment let me know.</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_10&diff=17881Introduction to JavaScript Fall 2010 Class 102010-11-09T22:04:54Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time. I also want to discuss '''anonymous functions''', which will be useful when we start using timers.<br />
<br />
== Anonymous Functions ==<br />
<br />
'''Anonymous functions''' are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class. This is what an anonymous function looks like:<br />
<br />
function() {<br />
// your code here<br />
}<br />
<br />
Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:<br />
<br />
Behavior.someFunction = '''function() {<br />
// your code here<br />
};'''<br />
<br />
Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass<br />
an anonymous function as a parameter to the jQuery ''click'' function:<br />
<br />
$("#button-id").click(function() {<br />
// code for handling the click event<br />
});<br />
<br />
The anonymous function will work exactly the same way this code:<br />
<br />
$("#button-id").click(handleClick);<br />
<br />
function handleClick() {<br />
// code for handling the click event<br />
}<br />
<br />
The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in<br />
to the click function.<br />
<br />
Anonymous functions will become more useful when we start working with timers.<br />
<br />
== JavaScript Timers ==<br />
<br />
Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay.<br />
Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.<br />
<br />
=== Using a Timer to Delay a Function Call ===<br />
<br />
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:<br />
<br />
$('#button-id').click(addParagraph);<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
You should already be familiar with this kind of thing, because we've done it in class.<br />
<br />
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.<br />
<br />
// When the button is clicked, create a new timer that will call the<br />
// addParagraph function after 2 seconds<br />
$('#button-id').click(function) {<br />
'''setTimeout(addParagraph, 2000);'''<br />
};<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:<br />
<br />
// Call '''functionName''' after 1 second<br />
setTimeout('''functionName''', 1000);<br />
<br />
Or it will take in an anonymous function that you want to be called:<br />
<br />
// Call the function block after 1 second<br />
setTimeout('''function() {'''<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).<br />
<br />
=== Using a Timer to Repeatedly Call a Function ===<br />
<br />
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:<br />
<br />
// Call '''myFunction''' every second<br />
setInterval('''myFunction''', 1000);<br />
<br />
Or:<br />
<br />
// Call the function block every second<br />
setInterval('''function() {<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.<br />
<br />
== Stopping Timers ==<br />
<br />
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?<br />
<br />
=== Stopping setTimeout ===<br />
<br />
When you call the '''setTimeout''' function it returns a value you can store in a variable:<br />
<br />
var timer = setTimeout(functionName, 1000);<br />
<br />
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.<br />
<br />
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:<br />
<br />
// Create a new timer and store it in the ''timer'' variable<br />
var timer = setTimeout(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// If 10 seconds haven't passed already this will cancel the timer<br />
// and the function will never get called<br />
clearTimeout(timer);<br />
<br />
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.<br />
<br />
=== Stopping setInterval ===<br />
<br />
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:<br />
<br />
var timer = setInterval(functionName, 1000);<br />
<br />
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:<br />
<br />
// Create a new timer and store it in the '''timer''' variable<br />
var timer = setInterval(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// Stop the timer from running. This will prevent the<br />
// timer from calling the function again<br />
clearInterval(timer);<br />
<br />
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.<br />
<br />
== Activity ==<br />
<br />
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.<br />
<br />
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter.zip here].<br />
<br />
<!--<br />
The completed version is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_10/counter_complete.zip here].<br />
--><br />
<br />
== Assignment 6 ==<br />
<br />
'''Due Friday December 4th at 10pm'''<br />
<br />
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:<br />
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''<br />
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.<br />
* Draw as many elements as you want, but draw at least 3 elements.<br />
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.<br />
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.<br />
<br />
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'cx' and 'cy' in the '''attr''' or '''animation''' functions:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// animate the circle to position x = 20, and y = 30<br />
circle.animate({ cx: 20, cy: 30 }, 200);<br />
<br />
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].<br />
<br />
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// change the color of the element when the user clicks on it<br />
circle.click(function()<br />
{<br />
circle.animate({ fill: '#6DBE9F' });<br />
});<br />
<br />
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2009_Class_9|JavaScript Art]] page from last week to see how to draw Raphael elements. <br />
<br />
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.<br />
<br />
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript/class_10/circles.zip here]. You can use it as a starting point if you'd like. <br />
<br />
'''We will show off our animations during class on December 9th.'''<br />
<br />
If you have any questions about the assignment let me know.</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_10&diff=17880Introduction to JavaScript Fall 2010 Class 102010-11-09T20:27:51Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time.<br />
<br />
== Anonymous Functions ==<br />
<br />
'''Anonymous functions''' are functions that don't have names. Although you might not realize it, you've already used anonymous functions in this class.<br />
<br />
This is what an anonymous function looks like this:<br />
<br />
function() {<br />
// your code here<br />
}<br />
<br />
Notice that the function doesn't have a name attached to it. In this class, we have been creating anonymous functions and then storing them on an object like this:<br />
<br />
Behavior.someFunction = '''function() {<br />
// your code here<br />
};'''<br />
<br />
Anonymous functions don't need to be stored in a variable or on an object. You can also pass anonymous functions around as parameters. For example, you could pass<br />
an anonymous function as a parameter to the jQuery ''click'' function:<br />
<br />
$("#button-id").click(function() {<br />
// code for handling the click event<br />
});<br />
<br />
The anonymous function will work exactly the same way this code:<br />
<br />
$("#button-id").click(handleClick);<br />
<br />
function handleClick() {<br />
// code for handling the click event<br />
}<br />
<br />
The only difference is that, in the first example, we didn't give a name to the handleClick function. We just created it as an anonymous function and passed it in<br />
to the click function.<br />
<br />
Anonymous functions will become more useful when we start working with timers.<br />
<br />
== JavaScript Timers ==<br />
<br />
Sometimes, you don't want run a function right away. Instead, you want the function to run after a delay.<br />
Other times, you want JavaScript to handle running the function repeatedly at a set interval. JavaScript timers allow you do both.<br />
<br />
=== Using a Timer to Delay a Function Call ===<br />
<br />
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in a function name or an anonymous function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that, when clicked, adds a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:<br />
<br />
$('#button-id').click(addParagraph);<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
You should already be familiar with this kind of thing, because we've done it in class.<br />
<br />
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.<br />
<br />
// When the button is clicked, create a new timer that will call the<br />
// addParagraph function after 2 seconds<br />
$('#button-id').click(function) {<br />
'''setTimeout(addParagraph, 2000);'''<br />
};<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:<br />
<br />
// Call '''functionName''' after 1 second<br />
setTimeout('''functionName''', 1000);<br />
<br />
Or it will take in an anonymous function that you want to be called:<br />
<br />
// Call the function block after 1 second<br />
setTimeout('''function() {'''<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
In both of these examples the functions will be called after 1000 milliseconds (remember, there are 1000 milliseconds in 1 second).<br />
<br />
=== Using a Timer to Repeatedly Call a Function ===<br />
<br />
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and a number in milliseconds as the second parameter:<br />
<br />
// Call '''myFunction''' every second<br />
setInterval('''myFunction''', 1000);<br />
<br />
Or:<br />
<br />
// Call the function block every second<br />
setInterval('''function() {<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.<br />
<br />
== Stopping Timers ==<br />
<br />
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?<br />
<br />
=== Stopping setTimeout ===<br />
<br />
When you call the '''setTimeout''' function it returns a value you can store in a variable:<br />
<br />
var timer = setTimeout(functionName, 1000);<br />
<br />
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.<br />
<br />
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:<br />
<br />
// Create a new timer and store it in the ''timer'' variable<br />
var timer = setTimeout(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// If 10 seconds haven't passed already this will cancel the timer<br />
// and the function will never get called<br />
clearTimeout(timer);<br />
<br />
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.<br />
<br />
=== Stopping setInterval ===<br />
<br />
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:<br />
<br />
var timer = setInterval(functionName, 1000);<br />
<br />
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:<br />
<br />
// Create a new timer and store it in the '''timer''' variable<br />
var timer = setInterval(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// Stop the timer from running. This will prevent the<br />
// timer from calling the function again<br />
clearInterval(timer);<br />
<br />
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.<br />
<br />
== Activity ==<br />
<br />
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.<br />
<br />
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript/class_10/counter.zip here].<br />
<br />
== Assignment 6 ==<br />
<br />
'''Due Friday December 4th at 10pm'''<br />
<br />
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:<br />
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''<br />
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.<br />
* Draw as many elements as you want, but draw at least 3 elements.<br />
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.<br />
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.<br />
<br />
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'cx' and 'cy' in the '''attr''' or '''animation''' functions:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// animate the circle to position x = 20, and y = 30<br />
circle.animate({ cx: 20, cy: 30 }, 200);<br />
<br />
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].<br />
<br />
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// change the color of the element when the user clicks on it<br />
circle.click(function()<br />
{<br />
circle.animate({ fill: '#6DBE9F' });<br />
});<br />
<br />
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2009_Class_9|JavaScript Art]] page from last week to see how to draw Raphael elements. <br />
<br />
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.<br />
<br />
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript/class_10/circles.zip here]. You can use it as a starting point if you'd like. <br />
<br />
'''We will show off our animations during class on December 9th.'''<br />
<br />
If you have any questions about the assignment let me know.</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_10&diff=17879Introduction to JavaScript Fall 2010 Class 102010-11-09T19:10:30Z<p>Matthew.ephraim: Created page with '== Introduction == This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a f…'</p>
<hr />
<div>== Introduction ==<br />
<br />
This week, I want to introduce you to the concept of JavaScript timers. Timers can be used to delay a function before it gets called or to repeatedly call a function over a period of time.<br />
<br />
== Using a Timer to Delay a Function Call ==<br />
<br />
The first type of timer uses the '''setTimeout''' function. The '''setTimeout''' function takes in another function as its first parameter and the number of milliseconds you'd like to delay before calling the function as the second parameter. For example, lets say you have a button that you want to add a new paragraph to a div called ''myDiv''. You could handle it with jQuery like this:<br />
<br />
$('#button-id').click(addParagraph);<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
You should already be familiar with this kind of thing, because we've done it in class.<br />
<br />
However, let's say that you didn't want to add the element to the page right away. Instead, you wanted to add the element after waiting for 2 seconds. You can use the '''setTimeout''' function to accomplish this.<br />
<br />
// When the button is clicked, create a new timer that will call the<br />
// addParagraph function after 2 seconds<br />
$('#button-id').click(function) {<br />
'''setTimeout(addParagraph, 2000);'''<br />
};<br />
<br />
function addParagraph() {<br />
$('#myDiv').append('&lt;p&gt;hello&lt;/p&gt;');<br />
}<br />
<br />
The setTimeout function above will delay the call to addParagraph for 2000 milliseconds, which is the same as 2 seconds. '''setTimeout''' will take in the name of a function as the first parameter:<br />
<br />
// Call '''functionName''' after 1 second<br />
setTimeout('''functionName''', 1000);<br />
<br />
Or it will take in an anonymous function that you want to be called:<br />
<br />
// Call the function block after 1 second<br />
setTimeout('''function() {'''<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
In both of these examples the functions will be called after 1000 milliseconds (or 1 second).<br />
<br />
== Using a Timer to Repeatedly Call a Function ==<br />
<br />
The second type of timer uses the '''setInterval''' function. Like the '''setTimeout''' function, the '''setInterval''' function takes in a function name or an anonymous function block as its first parameter and number in milliseconds as the second parameter:<br />
<br />
// Call '''myFunction''' every second<br />
setInterval('''myFunction''', 1000);<br />
<br />
Or:<br />
<br />
// Call the function block every second<br />
setInterval('''function() {<br />
// some code you want to be called<br />
}, 1000);<br />
<br />
What makes '''setInterval''' different is that it will repeatedly call the function, with a delay of milliseconds between each function call. In the examples above, the function will be called every 1000 milliseconds.<br />
<br />
== Stopping Timers ==<br />
<br />
Both '''setTimeout''' and '''setInterval''' are functions that will wait a number of milliseconds before calling another function. What if you called '''setTimeout''' or '''setInterval''', but then decided that you didn't want them to call the other function after all. How would you stop the function call from happening?<br />
<br />
=== Stopping setTimeout ===<br />
<br />
When you call the '''setTimeout''' function it returns a value you can store in a variable:<br />
<br />
var timer = setTimeout(functionName, 1000);<br />
<br />
If you have stored '''setTimeout's''' return value you can use that value with another function called '''clearTimeout'''. The '''clearTimeout''' function will stop the timer from running if it hasn't already run yet.<br />
<br />
For example, if I set a timer for 10,000 milliseconds (10 seconds), I can stop the timer before it runs and it will never call the function, even if 10 seconds goes by:<br />
<br />
// Create a new timer and store it in the ''timer'' variable<br />
var timer = setTimeout(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// If 10 seconds haven't passed already this will cancel the timer<br />
// and the function will never get called<br />
clearTimeout(timer);<br />
<br />
In the example above, '''setTimeout''' creates a new timer, which gets stored in the '''timer''' variable. Later on in the code '''clearTimeout''' stops the timer from running. If 10 seconds already have gone by, '''clearTimeout''' won't do anything.<br />
<br />
=== Stopping setInterval ===<br />
<br />
Just like the '''setTimeout''' function, '''setInterval''' returns a timer that you can store in a variable:<br />
<br />
var timer = setInterval(functionName, 1000);<br />
<br />
Once you have the timer that '''setInterval''' returned, you can use the '''clearInterval''' function to stop the timer from running. '''clearInterval''' takes in a timer variable and cancels the timer:<br />
<br />
// Create a new timer and store it in the '''timer''' variable<br />
var timer = setInterval(myFunction, 10000);<br />
<br />
... // whatever other code you might want to go here<br />
<br />
// Stop the timer from running. This will prevent the<br />
// timer from calling the function again<br />
clearInterval(timer);<br />
<br />
The '''clearInterval''' function will take the timer that his been running and stop it from running again. '''setInteval''' repeatedly calls a function until '''clearInterval''' stops it from running again.<br />
<br />
== Activity ==<br />
<br />
From this class, we will be using a template to build 2 timers. One that increments a number in a box, and one that creates a simple clock that counts up to 60 seconds and then resets itself.<br />
<br />
You can download the template for the activity [http://www.mattephraim.com/intro_to_javascript/class_10/counter.zip here].<br />
<br />
==Assignment 6==<br />
<br />
'''Due Friday December 4th at 10pm'''<br />
<br />
Your assignment this week is to create an animation that uses a timer to draw elements on the canvas. You can choose to draw any animation you want as long as it fulfills the following criteria:<br />
* It must use a timer to draw elements on the canvas, or to interact with elements on the canvas using either '''setTimeout''' or '''setInterval'''<br />
* It must draw multiple elements to the canvas. These can be circles, rectangles or whatever other shape is supported by Raphael.<br />
* Draw as many elements as you want, but draw at least 3 elements.<br />
* The elements must respond to a mouse event. The mouse event can be a click, a mouseover, mouseout or whatever other events are supported by Raphael.<br />
* The elements must change in some way in response to the mouse event. Remember that you can use the '''attr''' or '''animate''' functions to change the attributes on any Raphael element.<br />
<br />
The rest of the animation is up to you. Remember that you can change the x and y position of an element using 'cx' and 'cy' in the '''attr''' or '''animation''' functions:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// animate the circle to position x = 20, and y = 30<br />
circle.animate({ cx: 20, cy: 30 }, 200);<br />
<br />
A list of other attributes you can modify is [http://raphaeljs.com/reference.html#attr here].<br />
<br />
Also remember that you can attach mouse events to Raphael elements in the same way that you can attach events with jQuery:<br />
<br />
var circle = canvas.circle(5, 5, 10);<br />
<br />
// change the color of the element when the user clicks on it<br />
circle.click(function()<br />
{<br />
circle.animate({ fill: '#6DBE9F' });<br />
});<br />
<br />
Remember that you can find documentation and examples at the [http://raphaeljs.com/reference.html Raphael site], and you can use the [[Introduction_to_JavaScript_Fall_2009_Class_9|JavaScript Art]] page from last week to see how to draw Raphael elements. <br />
<br />
You can also see a list of jQuery's event handlers [http://docs.jquery.com/Events here] under '''Event helpers'''. Many of jQuery's helpers have the same names as Raphael's event helpers.<br />
<br />
I have posted a sample project that shows you the kind of thing I'm looking for [http://www.mattephraim.com/intro_to_javascript/class_10/circles.zip here]. You can use it as a starting point if you'd like. <br />
<br />
'''We will show off our animations during class on December 9th.'''<br />
<br />
If you have any questions about the assignment let me know.</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17858Introduction to JavaScript Fall 20102010-11-02T17:46:53Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* Class 9 (11/2/2010): [[Introduction_to_JavaScript_Fall_2010_Class_9|Raphaël]]<br />
<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17857Introduction to JavaScript Fall 20102010-11-02T17:44:32Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
* Class 9 (11/2/2010): [[Introduction_to_JavaScript_Fall_2010_Class_9|Raphael]]<br />
<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_9&diff=17856Introduction to JavaScript Fall 2010 Class 92010-11-02T17:33:02Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
This week I will be talking about how you can generate interactive artwork with JavaScript. There are several ways to create graphics with JavaScript, but, this week, I will be focusing on a specific browser feature called [http://en.wikipedia.org/wiki/Svg SVG]. I will show you how you can use the [http://raphaeljs.com/ Raphaël] library to easily generate interactive SVG graphics with JavaScript.<br />
<br />
== Graphics in JavaScript ==<br />
<br />
=== Few Options ===<br />
<br />
For most of JavaScript's history, there hasn't been a reliable way to use the language to draw images. There were various [http://en.wikipedia.org/wiki/Vml attempts] in the past, but none of were supported across all browsers. For the most part, the best bet for creating artwork in the browser (without a plugin) was to use HTML, CSS and image tags to create the graphics you wanted, and then use a little bit of JavaScript to make those element dynamic. Basic HTML tags were sufficient for simple graphics, but browser plugins, mainly [http://www.adobe.com/products/flashplayer/ Adobe Flash], soon took over as the tool of choice for artists and designers looking to create browser based artwork.<br />
<br />
=== SVG ===<br />
<br />
In 1999, the [http://en.wikipedia.org/wiki/W3C W3C] introduced a standard called Scalable Vector Graphics ([http://en.wikipedia.org/wiki/Svg SVG]). SVG is an XML based format that can be used to define graphics. Just like HTML is used to specify data that gets turned into webpages, SVG is a format that gets turned into images.<br />
<br />
SVG images are unlike other image formats that you're probably already familiar with. Instead of being [http://en.wikipedia.org/wiki/Bitmap bitmap] images (like JPEG and GIF) that are set as one fixed size, SVG files define vector graphics images. Images that are created with [http://en.wikipedia.org/wiki/Vector_graphics vector graphics] files are not set at any particular size. Instead, a vector graphics file defines a list of shapes that make up the image. Because of the way that these images are stored, vector graphics based images can be set to any size without degrading in quality. If you used Adobe Flash or Adobe Illustrator, you've used vector graphics, because both of these programs store their files in a vector graphics format (although, typically using a different format than SVG).<br />
<br />
In the browser, SVG has another feature that other images formats don't have: you can use JavaScript to draw, resize, or animate the images. And just like you can add event handlers to HTML elements, you can add JavaScript event handlers to SVG elements as well.<br />
<br />
=== Browser Support ===<br />
<br />
As I said earlier, SVG was introduced in 1999. And then...nothing happened. At the time, Internet Explorer was the most popular browser and had already introduced a competitor to SVG called VML. Additionally, the Netscape browser was quickly losing ground in the browser wars, and adding support for SVG wasn't high on their list of priorities. So, despite being already being a standard, SVG simply wasn't used in the browser.<br />
<br />
It wasn't until 2005, when Firefox added support for SVG documents, that using SVG in the browser actually became a realistic option. Today, all major browsers have at least some built in support for SVG. All browsers, except...you guessed it, Internet Explorer. There is hope though. The next version of Internet Explorer, version 9, is expected to have support for SVG built in.<br />
<br />
== Raphaël ==<br />
<br />
As you've already seen with jQuery, JavaScript libraries can streamline the code you have to write to make your page dynamic. This week, I want to introduce you to another library called [http://raphaeljs.com/ Raphaël]. Like jQuery, Raphaël is a library that helps to streamline your code. However, instead of helping you write code to make your HTML dynamic, Raphaël helps you write code to make your SVG dynamic. As an added benefit, Raphaël uses some trickery to automatically bring many SVG features to current versions of Internet Explorer.<br />
<br />
=== Creating the Canvas ===<br />
<br />
Before you can start drawing with Raphaël you need to have a canvas to draw on. You can use the '''Raphael''' function to create a new canvas. There are several ways to create a new canvas, including creating a canvas inside of an HTML element. You can start simple by creating an empty canvas right on your page:<br />
<br />
var canvas = Raphael(0, 0, 800, 600);<br />
<br />
The Raphael function takes in 4 parameters. The first two are x and y coordinates indicating the position where you'd like to create the canvas (in this example, it will be all the way in the top left corner). The second two parameters are for width and height and determine how large your canvas will be.<br />
<br />
=== Creating an Element on the Canvas ===<br />
<br />
Once you've created a new canvas, you can use canvas object to draw new elements. For example, you can create a new circle using the [http://raphaeljs.com/reference.html#circle '''circle'''] function:<br />
<br />
var circle = canvas.circle(50, 10, 60);<br />
<br />
This creates a new circle located 50 pixels to right on the canvas and 10 pixels down. The circle will have radius of 60 pixels. Similarly, you can create [http://raphaeljs.com/reference.html#rect rectangles] and [http://raphaeljs.com/reference.html#rect ellipses]. Follow the links to each shape to see the Raphaël [http://raphaeljs.com/reference.html documentation] for the element.<br />
<br />
=== Changing an Element's Attributes ===<br />
<br />
Just like jQuery, Raphaël gives you a function called '''attr''' that takes in an attributes object representing a collection of attributes you'd like to change for an element. However, instead of HTML attributes, Raphaël allows you to change SVG attributes. The Raphaël documentation provides a [http://raphaeljs.com/reference.html#attr list of attributes] that are commonly used. Some examples are below:<br />
<br />
// Create a new rectangle element<br />
var rect = canvas.rect(50, 50, 100, 100);<br />
<br />
// Change some attributes<br />
rect.attr({ width: 50, height: 50 }); // change the height and width<br />
rect.attr({ fill: '#5F93B1'}); // set an element's fill color<br />
rect.attr({ stroke: 'green' }); // set the stroke color for an element<br />
rect.attr(cx: 80, cy: 100); // move the element to position 80,100<br />
<br />
Just like the '''attr''' function or the similar '''css''' function in jQuery will update an element's attributes immediately, the '''attr''' function in Raphaël will update an element's attributes immediately as well.<br />
<br />
=== Animating an Element ===<br />
<br />
If, instead of changing an element's attributes immediately, you'd like to animate an element instead, you can use Raphaël's [http://raphaeljs.com/reference.html#animate '''animate'''] function to animate an element to a set of attributes. Just like the '''attr''' function, the '''animate''' function takes in an object representing a collection of attributes you'd like to change. However, '''animate''' also takes in a second parameter, which specifies how long you'd like the animation to last:<br />
<br />
// Create a new rectangle element at position 0,0<br />
var rect = canvas.rect(0, 0, 100, 100);<br />
<br />
// Animate the element to position 50, 50 in half a second<br />
rect.animate({ cx: 50, cy: 50}, 500);<br />
<br />
Raphaël's animate function is a little more flexible than jQuery's. Not only can you animate simple number values, but you can also animate some other attributes, such as fill and stroke colors.<br />
<br />
You can also pass in another function as a callback to the animate function. So if it you'd like another function to run when animation is complete, you can pass it in as the 3rd parameter:<br />
<br />
rect.animate({ stroke: 'blue'}, 500, afterAnimate);<br />
<br />
function afterAnimate() {<br />
rect.animate({ fill: 'red' });<br />
}<br />
<br />
The 3rd parameter is a '''callback''' function. Callbacks come in handy when you'd like multiple things to happen, but you need to wait for one function to be done before calling the next function.<br />
<br />
=== Adding Events to Elements ===<br />
<br />
Much like jQuery makes event handling for html elements a little bit easier, Raphaël gives you some functionality that makes event handling on SVG elements easier. In fact, the way that Raphaël allows you to add event handlers to SVG elements is almost identical to jQuery's method of adding event handlers to HTML elements:<br />
<br />
// On mouseover, change the size and color of the element<br />
rect.mouseover(handleMouseover);<br />
<br />
function handleMouseover() {<br />
this.animate({ height: 100, width: 100, fill: 'red' }, 200);<br />
}<br />
<br />
// On mouseout, shrink the element back down<br />
rect.mouseout(handleMouseout);<br />
<br />
function handleMouseout() {<br />
this.animate({ height: 50, width: 50, fill: 'blue' }, 200);<br />
}<br />
<br />
// On click, change the element's stroke color<br />
rect.click(handleClick);<br />
<br />
function handleClick() {<br />
this.attr({ stroke: "orange" });<br />
}<br />
<br />
Chances are, if an event handler works in jQuery, it also works in Raphaël. This can come in handy for creating graphics that you'd like the user to be able to interact with.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
* [http://www.phoboslab.org/biolab/ Biolab Disaster]<br />
<br />
== Activity 1==<br />
<br />
Follow along as I explain this Raphaël [http://mattephraim.com/intro_to_javascript_fall_2010/class_9/demo.zip example].<br />
<br />
Then take a look at the examples below to get any idea of what kinds of things you can do with Raphaël<br />
<br />
'''Raphaël Examples'''<br />
<br />
* [http://raphaeljs.com/pie.html Pie Chart]<br />
* [http://raphaeljs.com/analytics.html Line Chart]<br />
* [http://raphaeljs.com/chart.html Line Chart]<br />
* [http://raphaeljs.com/australia.html Map]<br />
* [http://raphaeljs.com/spin-spin-spin.html Spinner]<br />
* [http://raphaeljs.com/helvetica.html Type]<br />
* [http://raphaeljs.com/#demo More Demos]<br />
<br />
== Activity 2 ==<br />
<br />
Download the [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_9/raphael.zip template] and we'll build a simple interactive SVG graphic.<br />
<br />
<!-- * The completed activity is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_9/raphael_completed.zip here] --><br />
<br />
== Think About a Final Project ==<br />
<br />
Look back over the content we've covered in this class and start thinking about a final project you'd like to do. Maybe you have a project for another class<br />
you'd like to use JavaScript for or a project at work that could be improved with JavaScript. Next week, I'd like you have some ideas<br />
for what you'd like to do for a final class project.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_9&diff=17854Introduction to JavaScript Fall 2010 Class 92010-11-02T15:48:33Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
This week I will be talking about how you can generate interactive artwork with JavaScript. There are several ways to create graphics with JavaScript, but, this week, I will be focusing on a specific browser feature called [http://en.wikipedia.org/wiki/Svg SVG]. I will show you how you can use the [http://raphaeljs.com/ Raphaël] library to easily generate interactive SVG graphics with JavaScript.<br />
<br />
== Graphics in JavaScript ==<br />
<br />
=== Few Options ===<br />
<br />
For most of JavaScript's history, there hasn't been a reliable way to use the language to draw images. There were various [http://en.wikipedia.org/wiki/Vml attempts] in the past, but none of were supported across all browsers. For the most part, the best bet for creating artwork in the browser (without a plugin) was to use HTML, CSS and image tags to create the graphics you wanted, and then use a little bit of JavaScript to make those element dynamic. Basic HTML tags were sufficient for simple graphics, but browser plugins, mainly [http://www.adobe.com/products/flashplayer/ Adobe Flash], soon took over as the tool of choice for artists and designers looking to create browser based artwork.<br />
<br />
=== SVG ===<br />
<br />
In 1999, the [http://en.wikipedia.org/wiki/W3C W3C] introduced a standard called Scalable Vector Graphics ([http://en.wikipedia.org/wiki/Svg SVG]). SVG is an XML based format that can be used to define graphics. Just like HTML is used to specify data that gets turned into webpages, SVG is a format that gets turned into images.<br />
<br />
SVG images are unlike other image formats that you're probably already familiar with. Instead of being [http://en.wikipedia.org/wiki/Bitmap bitmap] images (like JPEG and GIF) that are set as one fixed size, SVG files define vector graphics images. Images that are created with [http://en.wikipedia.org/wiki/Vector_graphics vector graphics] files are not set at any particular size. Instead, a vector graphics file defines a list of shapes that make up the image. Because of the way that these images are stored, vector graphics based images can be set to any size without degrading in quality. If you used Adobe Flash or Adobe Illustrator, you've used vector graphics, because both of these programs store their files in a vector graphics format (although, typically using a different format than SVG).<br />
<br />
In the browser, SVG has another feature that other images formats don't have: you can use JavaScript to draw, resize, or animate the images. And just like you can add event handlers to HTML elements, you can add JavaScript event handlers to SVG elements as well.<br />
<br />
=== Browser Support ===<br />
<br />
As I said earlier, SVG was introduced in 1999. And then...nothing happened. At the time, Internet Explorer was the most popular browser and had already introduced a competitor to SVG called VML. Additionally, the Netscape browser was quickly losing ground in the browser wars, and adding support for SVG wasn't high on their list of priorities. So, despite being already being a standard, SVG simply wasn't used in the browser.<br />
<br />
It wasn't until 2005, when Firefox added support for SVG documents, that using SVG in the browser actually became a realistic option. Today, all major browsers have at least some built in support for SVG. All browsers, except...you guessed it, Internet Explorer. There is hope though. The next version of Internet Explorer, version 9, is expected to have support for SVG built in.<br />
<br />
== Raphaël ==<br />
<br />
As you've already seen with jQuery, JavaScript libraries can streamline the code you have to write to make your page dynamic. This week, I want to introduce you to another library called [http://raphaeljs.com/ Raphaël]. Like jQuery, Raphaël is a library that helps to streamline your code. However, instead of helping you write code to make your HTML dynamic, Raphaël helps you write code to make your SVG dynamic. As an added benefit, Raphaël uses some trickery to automatically bring many SVG features to current versions of Internet Explorer.<br />
<br />
=== Creating the Canvas ===<br />
<br />
Before you can start drawing with Raphaël you need to have a canvas to draw on. You can use the '''Raphael''' function to create a new canvas. There are several ways to create a new canvas, including creating a canvas inside of an HTML element. You can start simple by creating an empty canvas right on your page:<br />
<br />
var canvas = Raphael(0, 0, 800, 600);<br />
<br />
The Raphael function takes in 4 parameters. The first two are x and y coordinates indicating the position where you'd like to create the canvas (in this example, it will be all the way in the top left corner). The second two parameters are for width and height and determine how large your canvas will be.<br />
<br />
=== Creating an Element on the Canvas ===<br />
<br />
Once you've created a new canvas, you can use canvas object to draw new elements. For example, you can create a new circle using the [http://raphaeljs.com/reference.html#circle '''circle'''] function:<br />
<br />
var circle = canvas.circle(50, 10, 60);<br />
<br />
This creates a new circle located 50 pixels to right on the canvas and 10 pixels down. The circle will have radius of 60 pixels. Similarly, you can create [http://raphaeljs.com/reference.html#rect rectangles] and [http://raphaeljs.com/reference.html#rect ellipses]. Follow the links to each shape to see the Raphaël [http://raphaeljs.com/reference.html documentation] for the element.<br />
<br />
=== Changing an Element's Attributes ===<br />
<br />
Just like jQuery, Raphaël gives you a function called '''attr''' that takes in an attributes object representing a collection of attributes you'd like to change for an element. However, instead of HTML attributes, Raphaël allows you to change SVG attributes. The Raphaël documentation provides a [http://raphaeljs.com/reference.html#attr list of attributes] that are commonly used. Some examples are below:<br />
<br />
// Create a new rectangle element<br />
var rect = canvas.rect(50, 50, 100, 100);<br />
<br />
// Change some attributes<br />
rect.attr({ width: 50, height: 50 }); // change the height and width<br />
rect.attr({ fill: '#5F93B1'}); // set an element's fill color<br />
rect.attr({ stroke: 'green' }); // set the stroke color for an element<br />
rect.attr(cx: 80, cy: 100); // move the element to position 80,100<br />
<br />
Just like the '''attr''' function or the similar '''css''' function in jQuery will update an element's attributes immediately, the '''attr''' function in Raphaël will update an element's attributes immediately as well.<br />
<br />
=== Animating an Element ===<br />
<br />
If, instead of changing an element's attributes immediately, you'd like to animate an element instead, you can use Raphaël's [http://raphaeljs.com/reference.html#animate '''animate'''] function to animate an element to a set of attributes. Just like the '''attr''' function, the '''animate''' function takes in an object representing a collection of attributes you'd like to change. However, '''animate''' also takes in a second parameter, which specifies how long you'd like the animation to last:<br />
<br />
// Create a new rectangle element at position 0,0<br />
var rect = canvas.rect(0, 0, 100, 100);<br />
<br />
// Animate the element to position 50, 50 in half a second<br />
rect.animate({ cx: 50, cy: 50}, 500);<br />
<br />
Raphaël's animate function is a little more flexible than jQuery's. Not only can you animate simple number values, but you can also animate some other attributes, such as fill and stroke colors.<br />
<br />
You can also pass in another function as a callback to the animate function. So if it you'd like another function to run when animation is complete, you can pass it in as the 3rd parameter:<br />
<br />
rect.animate({ stroke: 'blue'}, 500, afterAnimate);<br />
<br />
function afterAnimate() {<br />
rect.animate({ fill: 'red' });<br />
}<br />
<br />
The 3rd parameter is a '''callback''' function. Callbacks come in handy when you'd like multiple things to happen, but you need to wait for one function to be done before calling the next function.<br />
<br />
=== Adding Events to Elements ===<br />
<br />
Much like jQuery makes event handling for html elements a little bit easier, Raphaël gives you some functionality that makes event handling on SVG elements easier. In fact, the way that Raphaël allows you to add event handlers to SVG elements is almost identical to jQuery's method of adding event handlers to HTML elements:<br />
<br />
// On mouseover, change the size and color of the element<br />
rect.mouseover(handleMouseover);<br />
<br />
function handleMouseover() {<br />
this.animate({ height: 100, width: 100, fill: 'red' }, 200);<br />
}<br />
<br />
// On mouseout, shrink the element back down<br />
rect.mouseout(handleMouseout);<br />
<br />
function handleMouseout() {<br />
this.animate({ height: 50, width: 50, fill: 'blue' }, 200);<br />
}<br />
<br />
// On click, change the element's stroke color<br />
rect.click(handleClick);<br />
<br />
function handleClick() {<br />
this.attr({ stroke: "orange" });<br />
}<br />
<br />
Chances are, if an event handler works in jQuery, it also works in Raphaël. This can come in handy for creating graphics that you'd like the user to be able to interact with.<br />
<br />
== Activity 1==<br />
<br />
Take a look at the examples below to get any idea of what kinds of things you can do with Raphaël<br />
<br />
'''Raphaël Examples'''<br />
<br />
* [http://raphaeljs.com/pie.html Pie Chart]<br />
* [http://raphaeljs.com/analytics.html Line Chart]<br />
* [http://raphaeljs.com/chart.html Line Chart]<br />
* [http://raphaeljs.com/australia.html Map]<br />
* [http://raphaeljs.com/spin-spin-spin.html Spinner]<br />
* [http://raphaeljs.com/helvetica.html Type]<br />
* [http://raphaeljs.com/#demo More Demos]<br />
<br />
== Activity 2 ==<br />
<br />
Download the [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_9/raphael.zip template] and we'll build a simple interactive SVG graphic.<br />
<br />
<!-- * The completed activity is [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_9/raphael_completed.zip here] --><br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_9&diff=17852Introduction to JavaScript Fall 2010 Class 92010-11-02T12:42:14Z<p>Matthew.ephraim: Created page with 'Back to Introduction to JavaScript Fall 2010 == Introduction == This week I will be talking about how you can generate interactive artw…'</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
This week I will be talking about how you can generate interactive artwork with JavaScript. There are several ways to create graphics with JavaScript, but, this week, I will be focusing on a specific browser feature called [http://en.wikipedia.org/wiki/Svg SVG]. I will show you how you can use the [http://raphaeljs.com/ Raphaël] library to easily generate interactive SVG graphics with JavaScript.<br />
<br />
== Graphics in JavaScript ==<br />
<br />
=== Few Options ===<br />
<br />
For most of JavaScript's history, there hasn't been a reliable way to use the language to draw images. There were various [http://en.wikipedia.org/wiki/Vml attempts] in the past, but none of were supported across all browsers. For the most part, the best bet for creating artwork in the browser (without a plugin) was to use HTML, CSS and image tags to create the graphics you wanted, and then use a little bit of JavaScript to make those element dynamic. Basic HTML tags were sufficient for simple graphics, but browser plugins, mainly [http://www.adobe.com/products/flashplayer/ Adobe Flash], soon took over as the tool of choice for artists and designers looking to create browser based artwork.<br />
<br />
=== SVG ===<br />
<br />
In 1999, the [http://en.wikipedia.org/wiki/W3C W3C] introduced a standard called Scalable Vector Graphics ([http://en.wikipedia.org/wiki/Svg SVG]). SVG is an XML based format that can be used to define graphics. Just like HTML is used to specify data that gets turned into webpages, SVG is a format that gets turned into images.<br />
<br />
SVG images are unlike other image formats that you're probably already familiar with. Instead of being [http://en.wikipedia.org/wiki/Bitmap bitmap] images (like JPEG and GIF) that are set as one fixed size, SVG files define vector graphics images. Images that are created with [http://en.wikipedia.org/wiki/Vector_graphics vector graphics] files are not set at any particular size. Instead, a vector graphics file defines a list of shapes that make up the image. Because of the way that these images are stored, vector graphics based images can be set to any size without degrading in quality. If you used Adobe Flash or Adobe Illustrator, you've used vector graphics, because both of these programs store their files in a vector graphics format (although, typically using a different format than SVG).<br />
<br />
In the browser, SVG has another feature that other images formats don't have: you can use JavaScript to draw, resize, or animate the images. And just like you can add event handlers to HTML elements, you can add JavaScript event handlers to SVG elements as well.<br />
<br />
=== Browser Support ===<br />
<br />
As I said earlier, SVG was introduced in 1999. And then...nothing happened. At the time, Internet Explorer was the most popular browser and had already introduced a competitor to SVG called VML. Additionally, the Netscape browser was quickly losing ground in the browser wars, and adding support for SVG wasn't high on their list of priorities. So, despite being already being a standard, SVG simply wasn't used in the browser.<br />
<br />
It wasn't until 2005, when Firefox added support for SVG documents, that using SVG in the browser actually became a realistic option. Today, all major browsers have at least some built in support for SVG. All browsers, except...you guessed it, Internet Explorer. There is hope though. The next version of Internet Explorer, version 9, is expected to have support for SVG built in.<br />
<br />
== Raphaël ==<br />
<br />
As you've already seen with jQuery, JavaScript libraries can streamline the code you have to write to make your page dynamic. This week, I want to introduce you to another library called [http://raphaeljs.com/ Raphaël]. Like jQuery, Raphaël is a library that helps to streamline your code. However, instead of helping you write code to make your HTML dynamic, Raphaël helps you write code to make your SVG dynamic. As an added benefit, Raphaël uses some trickery to automatically bring many SVG features to current versions of Internet Explorer.<br />
<br />
=== Creating the Canvas ===<br />
<br />
Before you can start drawing with Raphaël you need to have a canvas to draw on. You can use the '''Raphael''' function to create a new canvas. There are several ways to create a new canvas, including creating a canvas inside of an HTML element. You can start simple by creating an empty canvas right on your page:<br />
<br />
var canvas = Raphael(0, 0, 800, 600);<br />
<br />
The Raphael function takes in 4 parameters. The first two are x and y coordinates indicating the position where you'd like to create the canvas (in this example, it will be all the way in the top left corner). The second two parameters are for width and height and determine how large your canvas will be.<br />
<br />
=== Creating an Element on the Canvas ===<br />
<br />
Once you've created a new canvas, you can use canvas object to draw new elements. For example, you can create a new circle using the [http://raphaeljs.com/reference.html#circle '''circle'''] function:<br />
<br />
var circle = canvas.circle(50, 10, 60);<br />
<br />
This creates a new circle located 50 pixels to right on the canvas and 10 pixels down. The circle will have radius of 60 pixels. Similarly, you can create [http://raphaeljs.com/reference.html#rect rectangles] and [http://raphaeljs.com/reference.html#rect ellipses]. Follow the links to each shape to see the Raphaël [http://raphaeljs.com/reference.html documentation] for the element.<br />
<br />
=== Changing an Element's Attributes ===<br />
<br />
Just like jQuery, Raphaël gives you a function called '''attr''' that takes in an attributes object representing a collection of attributes you'd like to change for an element. However, instead of HTML attributes, Raphaël allows you to change SVG attributes. The Raphaël documentation provides a [http://raphaeljs.com/reference.html#attr list of attributes] that are commonly used. Some examples are below:<br />
<br />
// Create a new rectangle element<br />
var rect = canvas.rect(50, 50, 100, 100);<br />
<br />
// Change some attributes<br />
rect.attr({ width: 50, height: 50 }); // change the height and width<br />
rect.attr({ fill: '#5F93B1'}); // set an element's fill color<br />
rect.attr({ stroke: 'green' }); // set the stroke color for an element<br />
rect.attr(cx: 80, cy: 100); // move the element to position 80,100<br />
<br />
Just like the '''attr''' function or the similar '''css''' function in jQuery will update an element's attributes immediately, the '''attr''' function in Raphaël will update an element's attributes immediately as well.<br />
<br />
=== Animating an Element ===<br />
<br />
If, instead of changing an element's attributes immediately, you'd like to animate an element instead, you can use Raphaël's [http://raphaeljs.com/reference.html#animate '''animate'''] function to animate an element to a set of attributes. Just like the '''attr''' function, the '''animate''' function takes in an object representing a collection of attributes you'd like to change. However, '''animate''' also takes in a second parameter, which specifies how long you'd like the animation to last:<br />
<br />
// Create a new rectangle element at position 0,0<br />
var rect = canvas.rect(0, 0, 100, 100);<br />
<br />
// Animate the element to position 50, 50 in half a second<br />
rect.animate({ cx: 50, cy: 50}, 500);<br />
<br />
Raphaël's animate function is a little more flexible than jQuery's. Not only can you animate simple number values, but you can also animate some other attributes, such as fill and stroke colors.<br />
<br />
You can also pass in another function as a callback to the animate function. So if it you'd like another function to run when animation is complete, you can pass it in as the 3rd parameter:<br />
<br />
rect.animate({ stroke: 'blue'}, 500, afterAnimate);<br />
<br />
function afterAnimate() {<br />
rect.animate({ fill: 'red' });<br />
}<br />
<br />
The 3rd parameter is a '''callback''' function. Callbacks come in handy when you'd like multiple things to happen, but you need to wait for one function to be done before calling the next function.<br />
<br />
=== Adding Events to Elements ===<br />
<br />
Much like jQuery makes event handling for html elements a little bit easier, Raphaël gives you some functionality that makes event handling on SVG elements easier. In fact, the way that Raphaël allows you to add event handlers to SVG elements is almost identical to jQuery's method of adding event handlers to HTML elements:<br />
<br />
// On mouseover, change the size and color of the element<br />
rect.mouseover(handleMouseover);<br />
<br />
function handleMouseover() {<br />
this.animate({ height: 100, width: 100, fill: 'red' }, 200);<br />
}<br />
<br />
// On mouseout, shrink the element back down<br />
rect.mouseout(handleMouseout);<br />
<br />
function handleMouseout() {<br />
this.animate({ height: 50, width: 50, fill: 'blue' }, 200);<br />
}<br />
<br />
// On click, change the element's stroke color<br />
rect.click(handleClick);<br />
<br />
function handleClick() {<br />
this.attr({ stroke: "orange" });<br />
}<br />
<br />
Chances are, if an event handler works in jQuery, it also works in Raphaël. This can come in handy for creating graphics that you'd like the user to be able to interact with.<br />
<br />
== Activity 1==<br />
<br />
Take a look at the examples below to get any idea of what kinds of things you can do with Raphaël<br />
<br />
'''Raphaël Examples'''<br />
<br />
* [http://raphaeljs.com/pie.html Pie Chart]<br />
* [http://raphaeljs.com/analytics.html Line Chart]<br />
* [http://raphaeljs.com/chart.html Line Chart]<br />
* [http://raphaeljs.com/australia.html Map]<br />
* [http://raphaeljs.com/spin-spin-spin.html Spinner]<br />
* [http://raphaeljs.com/helvetica.html Type]<br />
* [http://raphaeljs.com/#demo More Demos]<br />
<br />
== Activity 2 ==<br />
<br />
Download the [http://www.mattephraim.com/intro_to_javascript/class_9/raphael.zip template] and we'll build a simple interactive SVG graphic.<br />
<br />
* The completed activity is [http://www.mattephraim.com/intro_to_javascript/class_9/raphael_completed.zip here]<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_8&diff=17833Introduction to JavaScript Fall 2010 Class 82010-10-26T19:01:11Z<p>Matthew.ephraim: /* Today's Interesting JavaScript Site */</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
In previous classes, we have talked about looking for elements with jQuery. When you use the<br />
jQuery function to find an element or multiple elements jQuery will return a jQuery ''"collection"''.<br />
So far, I haven't talked much about how jQuery collections work. This week, I will show you how to create<br />
your own collection of objects, and how to use jQuery to loop over each item in the collection.<br />
<br />
== Arrays ==<br />
<br />
Let's say that you wanted to create a shopping list using JavaSript. As an example, your shopping list might<br />
have the following items: '''milk, eggs, cheese and flour'''. Now let's say you wanted to make a function<br />
that would take care of the actions for buying each of the items. You might call your function ''buyStuff''.<br />
<br />
If you wanted to buy a single item, you could create a ''buyStuff'' function that takes one parameter:<br />
<br />
function buyStuff(item1) {<br />
// buy item 1<br />
}<br />
<br />
Then you could call your function like this:<br />
<br />
buyStuff("milk");<br />
<br />
But let's say you wanted to make a function that would buy multiple items. You would have to create a function<br />
that had a parameter for each item in your list. In the case of our example list, the function would need to have<br />
4 parameters, 1 for each item in the list.<br />
<br />
function buyStuff(item1, item2, item3, item4) {<br />
// buy item1<br />
// buy item2<br />
// buy item3<br />
// buy item4<br />
}<br />
<br />
This will work for now, but what if we added ''sugar'' to our list? Now the function would need to take in 5 parameters:<br />
<br />
function buyStuff(item1, item2, item3, item4, item5) {<br />
// buy item1<br />
// buy item2<br />
// buy item3<br />
// buy item4<br />
// buy item5<br />
}<br />
<br />
This works too, but now you can only have 5 items in your list. What if you wanted 10? Obviously, we need a way to pass a<br />
collection of items to the function.<br />
<br />
JavaScript allows you to create collections of objects called '''arrays'''. Think of an array as a box<br />
where you can store things. Using an array, we can create a shopping list of items that can be passed in as single parameter<br />
to a function.<br />
<br />
=== Creating an Array ===<br />
<br />
Arrays are created using an '''open straight bracket ([)''' and a '''close straight bracket (])'''. You can create an empty array<br />
and store it in a variable like this:<br />
<br />
var food = [];<br />
<br />
An empty array looks a little bit like an empty box, ready to have items added to it.<br />
<br />
=== Adding Items to an Array ===<br />
<br />
To add an item to an array, you use the '''push''' function. Push takes in a single object as a parameter. The item you pass in<br />
to push will be added as the last item in the array:<br />
<br />
var food = [];<br />
food.'''push'''("milk");<br />
food.'''push'''("eggs");<br />
food.'''push'''("cheese");<br />
food.'''push'''("flour");<br />
<br />
In the example above, an empty array called food is created, and multiple items are pushed into it. The first item in the array will<br />
be "milk" and the last item in the array will be "eggs".<br />
<br />
=== Array Literals ===<br />
<br />
Individually adding items to an array will work, but sometimes it can be tedious. You can create a new array that already has items in it<br />
by using an '''array literal'''. An array literal looks like this:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
Notice that the new array still has the open and close brackets, but this time the items for the array are listed between the brackets. Also notice<br />
that each item is separated by a comma.<br />
<br />
=== Accessing Array Items ===<br />
<br />
Once you have created an array, it would be nice to get the items out of the array. Each item in an array is numbered. However, instead of starting the<br />
numbering with 1, items in an array start with 0. If an array has 4 items, the first item will be number 0 and the last item will be number 3:<br />
<br />
var food = ["milk", // Item 0<br />
"eggs", // Item 1<br />
"cheese", // Item 2<br />
"flour"]; // Item 3<br />
<br />
To access an item in an array, take the name of the array you created and follow it with an open bracket, the number of the item you want to find, and finally<br />
a close bracket:<br />
<br />
alert(food[0]); // Alerts "milk"<br />
alert(food[1]); // Alerts "eggs"<br />
alert(food[3]); // Alerts "flour"<br />
<br />
If you use the ''push'' function to add new items to an array after it has been created, the new items will be added at the end of the array. So, if you add an item<br />
to an array that already has 4 items, the new item you add will be given the number 4.<br />
<br />
=== Checking the Number of Items in an Array ===<br />
<br />
If you have an array and you'd like to check the number of items in the array, you can use the array's '''length''' property. Just like JavaScript ''objects'', JavaScript<br />
arrays have some properties that you can get to through the dot (.) operator. You've already seen the array's ''push'' function, which is accessed through the dot operator. <br />
The array's '''length''' property is accessed through the dot operator as well:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
alert(food.'''length'''); // This should alert '''4'''<br />
<br />
An empty array has a length of 0 and when you add items to an array the length property will be updated automatically.<br />
<br />
=== Looping Through Array Items ===<br />
<br />
In [[Introduction_to_JavaScript_Fall_2010_Class_3|class 3]] I showed you how you could use ''loops'' to repeat some code a given number of times.<br />
You can also use loops to repeat some code for each item in an array. In the case of arrays, instead of supplying the number of times you'd like a<br />
loop to repeat, you will use the array's '''length''' property to determine the number of times a loop should repeat.<br />
<br />
Remember that loops need to have a variable that is incremented each time the loop runs. In previous examples we have used the variable '''i''', and then checked<br />
that '''i''' was less than a given number:<br />
<br />
for(var i = 0; i < 20; i++) {<br />
// run some code<br />
}<br />
<br />
When we loop over an array, we can still use the i variable to count off the number of times the loop has run. However, instead of checking that '''i''' is less<br />
than a certain number, we will check that it is less than the number of items in the array:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
for(var '''i''' = 0; '''i''' < food.length; '''i'''++) {<br />
alert(food['''i''']);<br />
}<br />
<br />
Remember that arrays start their numbering with 0 instead of 1. In the example above, we are using '''i''' to find an item in the array '''food'''. The loop<br />
will alert item 0 first, then item 1, then item 2 and so on. The loop will stop when i is the same as the '''food.length'''.<br />
<br />
== Updating the Shopping List ==<br />
<br />
Remember that, in the example above, we were trying to create function that would buy all of items in a shopping list. Using arrays, we can update the<br />
''buyStuff'' function so that it takes in an array as a parameter, and then loops over each item in the array:<br />
<br />
function buyStuff(food) {<br />
for(var i = 0; i < food.length; i++) {<br />
buy(food[i]);<br />
}<br />
}<br />
<br />
Then, we can use the function to buy all of the items on the list:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
buyStuff(food);<br />
<br />
With the new buyStuff function, we can update the list with more items withouth having to change the function.<br />
<br />
== Looping with jQuery ==<br />
<br />
You may have noticed that the syntax for looping over an array is a little bit ugly. jQuery provides a function that makes it easier to loop<br />
over arrays, as well as collections of items that you've found on the page.<br />
<br />
=== Wrapping an Array with jQuery ===<br />
<br />
First, to take advantage of jQuery's extra array functionality, you need to wrap your array with jQuery. This is as easy as using jQuery's '''$''' function:<br />
<br />
var food = '''$('''["milk", "eggs", "cheese", "flour"]''')''';<br />
<br />
Notice that the new array is created the same as before, but this time it's wrapped with '''$()'''. Once an array has be wrapped with jQuery, you can take<br />
advantage of the new functions that jQuery provides.<br />
<br />
=== Looping with jQuery ===<br />
<br />
Once of the new functions that jQuery provides is called '''each'''. The '''each''' function takes in another function that will be called for each item in the array.<br />
So, for example, let's say you wanted to alert each item in the array '''food'''. First, you need to create a function that will alert each individual item:<br />
<br />
function alertItem() {<br />
alert('''this''');<br />
}<br />
<br />
The ''alertItem'' function calls the ''alert'' function and passes in '''this'''. When we used jQuery event handlers, '''this''' pointed to the current item that was<br />
handling the event. With the '''each''' function, '''this''' points to the current item in the array. The example below shows how to loop over each item in the ''food''<br />
array:<br />
<br />
function alertItem() {<br />
alert('''this''');<br />
}<br />
<br />
var food = '''$('''["milk", "eggs", "cheese", "flour"]''')''';<br />
<br />
food.each(alertItem);<br />
<br />
The '''each''' function takes in the name of the '''alertItem''' function and calls the function for each item in the array. Every time the function runs, it will point<br />
to another item in the array. The first time it runs '''this''' will point to "milk". The second time it runs, it will point to "eggs". The function will run until it has<br />
been run for every item in the array.<br />
<br />
=== Using each with jQuery Collections ===<br />
<br />
The jQuery '''each''' function doesn't just work with arrays. It will also work with the special jQuery collections that are returned when you use jQuery to<br />
find elements on the page. For example, if you wanted to alert the html for every list item on the page, you could use the '''each''' function to do it:<br />
<br />
function alertHTML() {<br />
alert($(this).html());<br />
}<br />
<br />
$("li").each(alertHTML);<br />
<br />
jQuery will find every list item on the page and call the ''alertHTML'' function for each one.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://code.google.com/apis/ajax/playground/#jquery Google JavaScript playground]<br />
<br />
== Activities ==<br />
<br />
=== Activity 1 ===<br />
<br />
* Create a new page that uses jQuery.<br />
* Create an unordered list on the page (using the '''ul''' tag).<br />
* Create an array that has the following items: '''milk, eggs, cheese, flour'''.<br />
* Loop through each item in the array and add a new list item for each item.<br />
<br />
=== Activity 2 ===<br />
<br />
''You can update the code from activity 1 for activity 2''<br />
<br />
* Create a new page that uses jQuery.<br />
<br />
* Create 2 unordered lists on the page.<br />
** One list should have the id '''"grocery-list"'''.<br />
** The other list should the id '''"hardware-list"'''.<br />
<br />
* Create 2 textboxes on the page.<br />
** One textbox should have the id '''"grocery"'''.<br />
** The other textbox should have the id '''"hardware"'''.<br />
<br />
* Create a button for each textbox.<br />
** One button should have the id '''""add-grocery"'''.<br />
** The other button should have the id '''add-hardware'''.<br />
<br />
* When the add-grocery button is clicked, it should take the value of the grocery textbox and add a new list item to the grocery-list.<br />
* When the add-hardware button is clicked, it should take the value of the hardware textbox and add a new list item to the hardware-list.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17832Introduction to JavaScript Fall 20102010-10-26T17:34:39Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_8|Arrays]]<br />
<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17831Introduction to JavaScript Fall 20102010-10-26T17:34:23Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
* Class 8 (10/26/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Arrays]]<br />
<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_8&diff=17830Introduction to JavaScript Fall 2010 Class 82010-10-26T17:33:28Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
In previous classes, we have talked about looking for elements with jQuery. When you use the<br />
jQuery function to find an element or multiple elements jQuery will return a jQuery ''"collection"''.<br />
So far, I haven't talked much about how jQuery collections work. This week, I will show you how to create<br />
your own collection of objects, and how to use jQuery to loop over each item in the collection.<br />
<br />
== Arrays ==<br />
<br />
Let's say that you wanted to create a shopping list using JavaSript. As an example, your shopping list might<br />
have the following items: '''milk, eggs, cheese and flour'''. Now let's say you wanted to make a function<br />
that would take care of the actions for buying each of the items. You might call your function ''buyStuff''.<br />
<br />
If you wanted to buy a single item, you could create a ''buyStuff'' function that takes one parameter:<br />
<br />
function buyStuff(item1) {<br />
// buy item 1<br />
}<br />
<br />
Then you could call your function like this:<br />
<br />
buyStuff("milk");<br />
<br />
But let's say you wanted to make a function that would buy multiple items. You would have to create a function<br />
that had a parameter for each item in your list. In the case of our example list, the function would need to have<br />
4 parameters, 1 for each item in the list.<br />
<br />
function buyStuff(item1, item2, item3, item4) {<br />
// buy item1<br />
// buy item2<br />
// buy item3<br />
// buy item4<br />
}<br />
<br />
This will work for now, but what if we added ''sugar'' to our list? Now the function would need to take in 5 parameters:<br />
<br />
function buyStuff(item1, item2, item3, item4, item5) {<br />
// buy item1<br />
// buy item2<br />
// buy item3<br />
// buy item4<br />
// buy item5<br />
}<br />
<br />
This works too, but now you can only have 5 items in your list. What if you wanted 10? Obviously, we need a way to pass a<br />
collection of items to the function.<br />
<br />
JavaScript allows you to create collections of objects called '''arrays'''. Think of an array as a box<br />
where you can store things. Using an array, we can create a shopping list of items that can be passed in as single parameter<br />
to a function.<br />
<br />
=== Creating an Array ===<br />
<br />
Arrays are created using an '''open straight bracket ([)''' and a '''close straight bracket (])'''. You can create an empty array<br />
and store it in a variable like this:<br />
<br />
var food = [];<br />
<br />
An empty array looks a little bit like an empty box, ready to have items added to it.<br />
<br />
=== Adding Items to an Array ===<br />
<br />
To add an item to an array, you use the '''push''' function. Push takes in a single object as a parameter. The item you pass in<br />
to push will be added as the last item in the array:<br />
<br />
var food = [];<br />
food.'''push'''("milk");<br />
food.'''push'''("eggs");<br />
food.'''push'''("cheese");<br />
food.'''push'''("flour");<br />
<br />
In the example above, an empty array called food is created, and multiple items are pushed into it. The first item in the array will<br />
be "milk" and the last item in the array will be "eggs".<br />
<br />
=== Array Literals ===<br />
<br />
Individually adding items to an array will work, but sometimes it can be tedious. You can create a new array that already has items in it<br />
by using an '''array literal'''. An array literal looks like this:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
Notice that the new array still has the open and close brackets, but this time the items for the array are listed between the brackets. Also notice<br />
that each item is separated by a comma.<br />
<br />
=== Accessing Array Items ===<br />
<br />
Once you have created an array, it would be nice to get the items out of the array. Each item in an array is numbered. However, instead of starting the<br />
numbering with 1, items in an array start with 0. If an array has 4 items, the first item will be number 0 and the last item will be number 3:<br />
<br />
var food = ["milk", // Item 0<br />
"eggs", // Item 1<br />
"cheese", // Item 2<br />
"flour"]; // Item 3<br />
<br />
To access an item in an array, take the name of the array you created and follow it with an open bracket, the number of the item you want to find, and finally<br />
a close bracket:<br />
<br />
alert(food[0]); // Alerts "milk"<br />
alert(food[1]); // Alerts "eggs"<br />
alert(food[3]); // Alerts "flour"<br />
<br />
If you use the ''push'' function to add new items to an array after it has been created, the new items will be added at the end of the array. So, if you add an item<br />
to an array that already has 4 items, the new item you add will be given the number 4.<br />
<br />
=== Checking the Number of Items in an Array ===<br />
<br />
If you have an array and you'd like to check the number of items in the array, you can use the array's '''length''' property. Just like JavaScript ''objects'', JavaScript<br />
arrays have some properties that you can get to through the dot (.) operator. You've already seen the array's ''push'' function, which is accessed through the dot operator. <br />
The array's '''length''' property is accessed through the dot operator as well:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
alert(food.'''length'''); // This should alert '''4'''<br />
<br />
An empty array has a length of 0 and when you add items to an array the length property will be updated automatically.<br />
<br />
=== Looping Through Array Items ===<br />
<br />
In [[Introduction_to_JavaScript_Fall_2010_Class_3|class 3]] I showed you how you could use ''loops'' to repeat some code a given number of times.<br />
You can also use loops to repeat some code for each item in an array. In the case of arrays, instead of supplying the number of times you'd like a<br />
loop to repeat, you will use the array's '''length''' property to determine the number of times a loop should repeat.<br />
<br />
Remember that loops need to have a variable that is incremented each time the loop runs. In previous examples we have used the variable '''i''', and then checked<br />
that '''i''' was less than a given number:<br />
<br />
for(var i = 0; i < 20; i++) {<br />
// run some code<br />
}<br />
<br />
When we loop over an array, we can still use the i variable to count off the number of times the loop has run. However, instead of checking that '''i''' is less<br />
than a certain number, we will check that it is less than the number of items in the array:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
for(var '''i''' = 0; '''i''' < food.length; '''i'''++) {<br />
alert(food['''i''']);<br />
}<br />
<br />
Remember that arrays start their numbering with 0 instead of 1. In the example above, we are using '''i''' to find an item in the array '''food'''. The loop<br />
will alert item 0 first, then item 1, then item 2 and so on. The loop will stop when i is the same as the '''food.length'''.<br />
<br />
== Updating the Shopping List ==<br />
<br />
Remember that, in the example above, we were trying to create function that would buy all of items in a shopping list. Using arrays, we can update the<br />
''buyStuff'' function so that it takes in an array as a parameter, and then loops over each item in the array:<br />
<br />
function buyStuff(food) {<br />
for(var i = 0; i < food.length; i++) {<br />
buy(food[i]);<br />
}<br />
}<br />
<br />
Then, we can use the function to buy all of the items on the list:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
buyStuff(food);<br />
<br />
With the new buyStuff function, we can update the list with more items withouth having to change the function.<br />
<br />
== Looping with jQuery ==<br />
<br />
You may have noticed that the syntax for looping over an array is a little bit ugly. jQuery provides a function that makes it easier to loop<br />
over arrays, as well as collections of items that you've found on the page.<br />
<br />
=== Wrapping an Array with jQuery ===<br />
<br />
First, to take advantage of jQuery's extra array functionality, you need to wrap your array with jQuery. This is as easy as using jQuery's '''$''' function:<br />
<br />
var food = '''$('''["milk", "eggs", "cheese", "flour"]''')''';<br />
<br />
Notice that the new array is created the same as before, but this time it's wrapped with '''$()'''. Once an array has be wrapped with jQuery, you can take<br />
advantage of the new functions that jQuery provides.<br />
<br />
=== Looping with jQuery ===<br />
<br />
Once of the new functions that jQuery provides is called '''each'''. The '''each''' function takes in another function that will be called for each item in the array.<br />
So, for example, let's say you wanted to alert each item in the array '''food'''. First, you need to create a function that will alert each individual item:<br />
<br />
function alertItem() {<br />
alert('''this''');<br />
}<br />
<br />
The ''alertItem'' function calls the ''alert'' function and passes in '''this'''. When we used jQuery event handlers, '''this''' pointed to the current item that was<br />
handling the event. With the '''each''' function, '''this''' points to the current item in the array. The example below shows how to loop over each item in the ''food''<br />
array:<br />
<br />
function alertItem() {<br />
alert('''this''');<br />
}<br />
<br />
var food = '''$('''["milk", "eggs", "cheese", "flour"]''')''';<br />
<br />
food.each(alertItem);<br />
<br />
The '''each''' function takes in the name of the '''alertItem''' function and calls the function for each item in the array. Every time the function runs, it will point<br />
to another item in the array. The first time it runs '''this''' will point to "milk". The second time it runs, it will point to "eggs". The function will run until it has<br />
been run for every item in the array.<br />
<br />
=== Using each with jQuery Collections ===<br />
<br />
The jQuery '''each''' function doesn't just work with arrays. It will also work with the special jQuery collections that are returned when you use jQuery to<br />
find elements on the page. For example, if you wanted to alert the html for every list item on the page, you could use the '''each''' function to do it:<br />
<br />
function alertHTML() {<br />
alert($(this).html());<br />
}<br />
<br />
$("li").each(alertHTML);<br />
<br />
jQuery will find every list item on the page and call the ''alertHTML'' function for each one.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://www.phoboslab.org/biolab/ Biolab Disaster]<br />
<br />
== Activities ==<br />
<br />
=== Activity 1 ===<br />
<br />
* Create a new page that uses jQuery.<br />
* Create an unordered list on the page (using the '''ul''' tag).<br />
* Create an array that has the following items: '''milk, eggs, cheese, flour'''.<br />
* Loop through each item in the array and add a new list item for each item.<br />
<br />
=== Activity 2 ===<br />
<br />
''You can update the code from activity 1 for activity 2''<br />
<br />
* Create a new page that uses jQuery.<br />
<br />
* Create 2 unordered lists on the page.<br />
** One list should have the id '''"grocery-list"'''.<br />
** The other list should the id '''"hardware-list"'''.<br />
<br />
* Create 2 textboxes on the page.<br />
** One textbox should have the id '''"grocery"'''.<br />
** The other textbox should have the id '''"hardware"'''.<br />
<br />
* Create a button for each textbox.<br />
** One button should have the id '''""add-grocery"'''.<br />
** The other button should have the id '''add-hardware'''.<br />
<br />
* When the add-grocery button is clicked, it should take the value of the grocery textbox and add a new list item to the grocery-list.<br />
* When the add-hardware button is clicked, it should take the value of the hardware textbox and add a new list item to the hardware-list.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_8&diff=17829Introduction to JavaScript Fall 2010 Class 82010-10-26T17:32:22Z<p>Matthew.ephraim: Created page with 'Back to Introduction to JavaScript Fall 2010 == Introduction == In previous classes, we have talked about looking for elements with jQu…'</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
In previous classes, we have talked about looking for elements with jQuery. When you use the<br />
jQuery function to find an element or multiple elements jQuery will return a jQuery ''"collection"''.<br />
So far, I haven't talked much about how jQuery collections work. This week, I will show you how to create<br />
your own collection of objects, and how to use jQuery to loop over each item in the collection.<br />
<br />
== Arrays ==<br />
<br />
Let's say that you wanted to create a shopping list using JavaSript. As an example, your shopping list might<br />
have the following items: '''milk, eggs, cheese and flour'''. Now let's say you wanted to make a function<br />
that would take care of the actions for buying each of the items. You might call your function ''buyStuff''.<br />
<br />
If you wanted to buy a single item, you could create a ''buyStuff'' function that takes one parameter:<br />
<br />
function buyStuff(item1) {<br />
// buy item 1<br />
}<br />
<br />
Then you could call your function like this:<br />
<br />
buyStuff("milk");<br />
<br />
But let's say you wanted to make a function that would buy multiple items. You would have to create a function<br />
that had a parameter for each item in your list. In the case of our example list, the function would need to have<br />
4 parameters, 1 for each item in the list.<br />
<br />
function buyStuff(item1, item2, item3, item4) {<br />
// buy item1<br />
// buy item2<br />
// buy item3<br />
// buy item4<br />
}<br />
<br />
This will work for now, but what if we added ''sugar'' to our list? Now the function would need to take in 5 parameters:<br />
<br />
function buyStuff(item1, item2, item3, item4, item5) {<br />
// buy item1<br />
// buy item2<br />
// buy item3<br />
// buy item4<br />
// buy item5<br />
}<br />
<br />
This works too, but now you can only have 5 items in your list. What if you wanted 10? Obviously, we need a way to pass a<br />
collection of items to the function.<br />
<br />
JavaScript allows you to create collections of objects called '''arrays'''. Think of an array as a box<br />
where you can store things. Using an array, we can create a shopping list of items that can be passed in as single parameter<br />
to a function.<br />
<br />
=== Creating an Array ===<br />
<br />
Arrays are created using an '''open straight bracket ([)''' and a '''close straight bracket (])'''. You can create an empty array<br />
and store it in a variable like this:<br />
<br />
var food = [];<br />
<br />
An empty array looks a little bit like an empty box, ready to have items added to it.<br />
<br />
=== Adding Items to an Array ===<br />
<br />
To add an item to an array, you use the '''push''' function. Push takes in a single object as a parameter. The item you pass in<br />
to push will be added as the last item in the array:<br />
<br />
var food = [];<br />
food.'''push'''("milk");<br />
food.'''push'''("eggs");<br />
food.'''push'''("cheese");<br />
food.'''push'''("flour");<br />
<br />
In the example above, an empty array called food is created, and multiple items are pushed into it. The first item in the array will<br />
be "milk" and the last item in the array will be "eggs".<br />
<br />
=== Array Literals ===<br />
<br />
Individually adding items to an array will work, but sometimes it can be tedious. You can create a new array that already has items in it<br />
by using an '''array literal'''. An array literal looks like this:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
Notice that the new array still has the open and close brackets, but this time the items for the array are listed between the brackets. Also notice<br />
that each item is separated by a comma.<br />
<br />
=== Accessing Array Items ===<br />
<br />
Once you have created an array, it would be nice to get the items out of the array. Each item in an array is numbered. However, instead of starting the<br />
numbering with 1, items in an array start with 0. If an array has 4 items, the first item will be number 0 and the last item will be number 3:<br />
<br />
var food = ["milk", // Item 0<br />
"eggs", // Item 1<br />
"cheese", // Item 2<br />
"flour"]; // Item 3<br />
<br />
To access an item in an array, take the name of the array you created and follow it with an open bracket, the number of the item you want to find, and finally<br />
a close bracket:<br />
<br />
alert(food[0]); // Alerts "milk"<br />
alert(food[1]); // Alerts "eggs"<br />
alert(food[3]); // Alerts "flour"<br />
<br />
If you use the ''push'' function to add new items to an array after it has been created, the new items will be added at the end of the array. So, if you add an item<br />
to an array that already has 4 items, the new item you add will be given the number 4.<br />
<br />
=== Checking the Number of Items in an Array ===<br />
<br />
If you have an array and you'd like to check the number of items in the array, you can use the array's '''length''' property. Just like JavaScript ''objects'', JavaScript<br />
arrays have some properties that you can get to through the dot (.) operator. You've already seen the array's ''push'' function, which is accessed through the dot operator. <br />
The array's '''length''' property is accessed through the dot operator as well:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
alert(food.'''length'''); // This should alert '''4'''<br />
<br />
An empty array has a length of 0 and when you add items to an array the length property will be updated automatically.<br />
<br />
=== Looping Through Array Items ===<br />
<br />
In [[Introduction_to_JavaScript_Fall_2010_Class_3|class 3]] I showed you how you could use ''loops'' to repeat some code a given number of times.<br />
You can also use loops to repeat some code for each item in an array. In the case of arrays, instead of supplying the number of times you'd like a<br />
loop to repeat, you will use the array's '''length''' property to determine the number of times a loop should repeat.<br />
<br />
Remember that loops need to have a variable that is incremented each time the loop runs. In previous examples we have used the variable '''i''', and then checked<br />
that '''i''' was less than a given number:<br />
<br />
for(var i = 0; i < 20; i++) {<br />
// run some code<br />
}<br />
<br />
When we loop over an array, we can still use the i variable to count off the number of times the loop has run. However, instead of checking that '''i''' is less<br />
than a certain number, we will check that it is less than the number of items in the array:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
for(var '''i''' = 0; '''i''' < food.length; '''i'''++) {<br />
alert(food['''i''']);<br />
}<br />
<br />
Remember that arrays start their numbering with 0 instead of 1. In the example above, we are using '''i''' to find an item in the array '''food'''. The loop<br />
will alert item 0 first, then item 1, then item 2 and so on. The loop will stop when i is the same as the '''food.length'''.<br />
<br />
== Updating the Shopping List ==<br />
<br />
Remember that, in the example above, we were trying to create function that would buy all of items in a shopping list. Using arrays, we can update the<br />
''buyStuff'' function so that it takes in an array as a parameter, and then loops over each item in the array:<br />
<br />
function buyStuff(food) {<br />
for(var i = 0; i < food.length; i++) {<br />
buy(food[i]);<br />
}<br />
}<br />
<br />
Then, we can use the function to buy all of the items on the list:<br />
<br />
var food = ["milk", "eggs", "cheese", "flour"];<br />
<br />
buyStuff(food);<br />
<br />
With the new buyStuff function, we can update the list with more items withouth having to change the function.<br />
<br />
== Looping with jQuery ==<br />
<br />
You may have noticed that the syntax for looping over an array is a little bit ugly. jQuery provides a function that makes it easier to loop<br />
over arrays, as well as collections of items that you've found on the page.<br />
<br />
=== Wrapping an Array with jQuery ===<br />
<br />
First, to take advantage of jQuery's extra array functionality, you need to wrap your array with jQuery. This is as easy as using jQuery's '''$''' function:<br />
<br />
var food = '''$('''["milk", "eggs", "cheese", "flour"]''')''';<br />
<br />
Notice that the new array is created the same as before, but this time it's wrapped with '''$()'''. Once an array has be wrapped with jQuery, you can take<br />
advantage of the new functions that jQuery provides.<br />
<br />
=== Looping with jQuery ===<br />
<br />
Once of the new functions that jQuery provides is called '''each'''. The '''each''' function takes in another function that will be called for each item in the array.<br />
So, for example, let's say you wanted to alert each item in the array '''food'''. First, you need to create a function that will alert each individual item:<br />
<br />
function alertItem() {<br />
alert('''this''');<br />
}<br />
<br />
The ''alertItem'' function calls the ''alert'' function and passes in '''this'''. When used jQuery event handlers, '''this''' pointed to the current item that was<br />
handling the event. With the '''each''' function, '''this''' points to the current item in the array. The example below shows how to loop over each item in the ''food''<br />
array:<br />
<br />
function alertItem() {<br />
alert('''this''');<br />
}<br />
<br />
var food = '''$('''["milk", "eggs", "cheese", "flour"]''')''';<br />
<br />
food.each(alertItem);<br />
<br />
The '''each''' function takes in the name of the '''alertItem''' function and calls the function for each item in the array. Every time the function runs, it will point<br />
to another item in the array. The first time it runs '''this''' will point to "milk". The second time it runs, it will point to "eggs". The function will run until it has<br />
been run for every item in the array.<br />
<br />
=== Using each with jQuery Collections ===<br />
<br />
The jQuery '''each''' function doesn't just work with arrays. It will also work with the special jQuery collections that are returned when you use jQuery to<br />
find elements on the page. For example, if you wanted to alert the html for every list item on the page, you could use the '''each''' function to do it:<br />
<br />
function alertHTML() {<br />
alert($(this).html());<br />
}<br />
<br />
$("li").each(alertHTML);<br />
<br />
jQuery will find every list item on the page and call the ''alertHTML'' function for each one.<br />
<br />
== Activities ==<br />
<br />
=== Activity 1 ===<br />
<br />
* Create a new page that uses jQuery.<br />
* Create an unordered list on the page (using the <code><ul></ul></code> tag).<br />
* Create an array that has the following items: '''milk, eggs, cheese, flour'''.<br />
* Loop through each item in the array and add a new list item for each item.<br />
<br />
=== Activity 2 ===<br />
<br />
''You can update the code from activity 1 for activity 2''<br />
<br />
* Create a new page that uses jQuery.<br />
<br />
* Create 2 unordered lists on the page.<br />
** One list should have the id '''"grocery-list"'''.<br />
** The other list should the id '''"hardware-list"'''.<br />
<br />
* Create 2 textboxes on the page.<br />
** One textbox should have the id '''"grocery"'''.<br />
** The other textbox should have the id '''"hardware"'''.<br />
<br />
* Create a button for each textbox.<br />
** One button should have the id '''""add-grocery"'''.<br />
** The other button should have the id '''add-hardware'''.<br />
<br />
* When the add-grocery button is clicked, it should take the value of the grocery textbox and add a new list item to the grocery-list.<br />
* When the add-hardware button is clicked, it should take the value of the hardware textbox and add a new list item to the hardware-list.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17796Introduction to JavaScript Fall 20102010-10-19T23:42:15Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
* Class 7 (10/19/2010): [[Introduction_to_JavaScript_Fall_2010_Class_7|Forms and More jQuery]]<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_7&diff=17795Introduction to JavaScript Fall 2010 Class 72010-10-19T23:01:32Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
So far, I've shown you how to handle a user's interactions with page. You've seen how to handle user events like '''click''' and '''mouseover'''.<br />
And you've seen how you can use jQuery to modify elements on the page. One thing I haven't shown you, however, is how you can let a user add<br />
new elements to the page.<br />
<br />
This week, I will show you how you can read in values from form elements on the page and how you can use user entered data to<br />
allow a user to modify page elements.<br />
<br />
== HTML Forms ==<br />
<br />
The HTML form tag allow users to enter information and submit that information to a server. With JavaScript, you can also do things with the<br />
information that a user entered.<br />
<br />
=== Getting the Values From a Form ===<br />
<br />
If you want to get the value of an input element, you'll need to find the element first. Then, once you've found the<br />
input element, you can use the [http://docs.jquery.com/Val '''val'''] function to get the value of the element.<br />
<br />
Let's say I have a form that looks like this:<br />
<br />
<form><br />
<input id="first-name" name="first-name" /><br />
<input id="last-name" name="last-name" /><br />
</form><br />
<br />
If I want to get the value of the '''first-name''' input, I can get to it like this:<br />
<br />
var firstNameField = $('#first-name');<br />
var firstName = firstNameField.val();<br />
<br />
Similarly, I can get to the last name input value like this:<br />
<br />
var lastNameField = $('#last-name');<br />
var lastName = lastNameField.val();<br />
<br />
In both cases, I'm simply finding the element and pulling the value out of it with '''val'''.<br />
<br />
Also, remember that you can always use the shorthand version of the above code like this:<br />
<br />
var firstName = $('#first-name').val();<br />
var lastName = $('#last-name').val();<br />
<br />
Both ways of finding the value are valid. Many people prefer the second method because it's shorter.<br />
<br />
=== Triming Whitespace ===<br />
<br />
Sometimes, you may need to make sure that you're not getting any extra information that you don't want from an input. For example,<br />
a user might accidentally put a space at the end of the value they entered in a textbox. You probably don't want that extra space, but, by default<br />
JavaScript will include it. So, if a user enters '''"Matthew "''' in the textbox, you'll get that extra space at the end.<br />
<br />
jQuery includes a function called [http://docs.jquery.com/Utilities/jQuery.trim trim] to get rid of any extra whitespace at the beginning or end of a string:<br />
<br />
var lastName = $('#last-name').val();<br />
var lastNameTrimmed = $.trim(lastName);<br />
<br />
In the example above, if the '''last-name''' input has any extra whitespace at the beginning or the end, the '''trim''' function will get rid of it.<br />
<br />
== Adding New Elements to the Page ==<br />
<br />
jQuery allows you to update an element's html by using the '''html''' function:<br />
<br />
var element = $('#my-element');<br />
<br />
// Change an element's html to "Some new text"<br />
element.html("Some new text");<br />
<br />
This works fine, but sometimes you want to do things that are a little bit more complicated.<br />
Let's say that you had an unordered list of items on the page and you wanted to use JavaScript to<br />
add a new item to the list. Using the html function, the only way you could do that would be to modify the HTML inside of the list:<br />
<br />
'''// DON'T DO THIS!!!!!'''<br />
var listHTML = $('#my-list').html();<br />
listHTML = listHTML + &quot;&lt;li&gt;New List Item&lt;/li&gt;&quot;;<br />
$('#my-list').html(listHTML);<br />
'''// DON'T DO THIS!!!!!'''<br />
<br />
Doing things this way works, but it's not very flexible or pretty. jQuery offers a better way.<br />
<br />
=== Creating Elements With jQuery ===<br />
<br />
So far, we've been using jQuery to select items on the page using their tag names, ids or css classes. That's not all you can<br />
do with jQuery though. You can also use jQuery to create new elements for your page. To do this, you simply need to pass<br />
a string of HTML to the jQuery function. jQuery will take the string of HTML and create a new element with it:<br />
<br />
var newListItem = $('&lt;li&gt;My new list item&lt;/li&gt;');<br />
<br />
The variable called '''newListItem''' is now set to a list item element that says ''My new list item'' inside of it. The next step<br />
is actually adding the element to the page<br />
<br />
=== Adding Elements to the Page ===<br />
<br />
jQuery offers a number of ways to add elements to your page. We will cover a few simple ones today.<br />
<br />
Suppose there's an unordered list that already has two items in it:<br />
<br />
&lt;ul id=&quot;my-list&quot;&gt;<br />
&lt;li&gt;Item 1&lt;/li&gt;<br />
&lt;li&gt;Item 2&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
Above, I created a new element called '''myListItem'''. If I want to add it to the end of '''my-list''' I can use jQuery to find the<br />
list and then use the [http://docs.jquery.com/Manipulation/append '''append'''] function to add the list item to the end:<br />
<br />
var newListItem = $('&lt;li&gt;My new list item&lt;/li&gt;');<br />
var list = $('#my-list');<br />
<br />
list.append(newListItem);<br />
<br />
I can even shorten it up a little bit:<br />
<br />
$('#my-list').append($('&lt;li&gt;My new list item&lt;/li&gt;'));<br />
<br />
Similarly, if I want to add the new list item to the beginning of the list, before all of the other list items, I can use the<br />
[http://docs.jquery.com/Manipulation/prepend '''prepend'''] function:<br />
<br />
$('#my-list').prepend($('&lt;li&gt;My new list item&lt;/li&gt;'));<br />
<br />
jQuery's '''append''' and '''prepend''' functions will both take one element and modify it by adding a new element to it. This gives you the same<br />
result as modifying the element's HTML, but also gives you more flexibility. Any new element that you create with jQuery can also be modified by<br />
jQuery, which includes adding class names, new attributes and event handlers.<br />
<br />
== Functions That Return Values ==<br />
<br />
Early in the class we talked a little bit about how you can create functions and how you can return values from those functions. But, so far,<br />
we haven't created our own functions that return a value.<br />
<br />
JavaScript functions are useful for encapsulating pieces of code that you want to run. Sometimes that code needs to send something back to <br />
the original code that called the function. The '''return''' keyword allows you to return one value back from the function.<br />
<br />
Today's activity involves checking a form to make sure that all of the elements are filled out. A useful function for the activity might<br />
be a function that returns '''true''' if all of the fields are filled out and returns '''false''' if any of the fields are empty. The<br />
basic structure of that function would look like this:<br />
<br />
function allFilledOut() {<br />
if (all of the fields are filled out) {<br />
return true;<br />
} else {<br />
return false;<br />
}<br />
}<br />
<br />
This code, of course, doesn't do anything yet because the if statement isn't actual code. However, the important part is the structure. I'm checking<br />
to make sure that all of the fields are filled out. If that statement turns out to be true, then the function returns '''true'''. Otherwise, the function<br />
returns false. Later, if I wanted to use the new '''allFilledOut''' function, I could call it in another piece of code and use the value that was returned:<br />
<br />
var '''completed''' = '''allFilledOut'''();<br />
if ('''completed''') {<br />
alert('The form is complete!');<br />
} else {<br />
alert('You still have things to fill out!')';<br />
}<br />
<br />
There are a few things to notice here. One is that I'm storing the '''return value''' of the '''allFilledOut''' function in a variable called '''completed'''.<br />
So, this variable will either be '''true''' or '''false''' after the function runs. Do I really need to create this variable though? Notice that I've also<br />
named my function '''allFilledOut'''. It might make sense to just put a call to that function right in my if statement like this:<br />
<br />
if ('''allFilledOut'''()) {<br />
alert('The form is complete!');<br />
} else {<br />
alert('You still have things to fill out!')';<br />
}<br />
<br />
Now the if statement looks more like a statement in English: ''if all of the fields are filled out then do one thing, or else do the other thing''. When you're<br />
creating functions that return true or false, it helps to name the functions in a way that makes your code read like you might write it out in regular English.<br />
<br />
Functions don't have to only return true and false values though. You can also use them return anything. For example, I might want a function that takes in a<br />
list of words and returns them as one string, separated by commas:<br />
<br />
function makeList(wordOne, wordTwo, wordThree) {<br />
var list = wordOne + ", " + wordTwo + ", " + wordThree;<br />
return list;<br />
}<br />
<br />
// Food should equal "pizza, burgers, popcorn"<br />
var food = makeSentence('pizza', 'burgers', 'popcorn'); <br />
<br />
The function called '''makeList''' takes in 3 parameters and builds a string that has all three parameters joined together as a list.<br />
<br />
== Today's Interesting JavaScript Sites ==<br />
<br />
* [http://www.phoboslab.org/files/venetianization/ Audio + Canvas Tag Animation]<br />
* [http://mrdoob.com/98/3D_Waveform_HTML5 Another Audio + Canvas Tag Animation]<br />
<br />
== Activity 1 ==<br />
<br />
For tonight's activity, we will be creating a page that has a form that allows you add new messages to a page. There are two JavaScript files<br />
associated with this activity. The first one, called '''validation.js''', will handle validating the form field. In this case, if a form field<br />
has a class of '''required''' on it, the field will need to be filled out before the message can be added. If the user leaves any fields blank,<br />
they should get an error message and the required fields that were left blank should get a class called '''error''' added to them.<br />
<br />
The second JavaScript file, called '''messages.js''' will add new messages to the list on the right.<br />
<br />
The template for tonight's activity can be found [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_7/messages.zip here].<br />
<br />
== Assignment 4 ==<br />
<br />
'''Due Friday October 29th at 10pm '''<br />
<br />
So far, I've given you a template for each of your assignments. For this assignment, I want you to come up with a page and some JavaScript code that <br />
goes with the page on your own.<br />
<br />
Your page needs to have a textbox that will take in the url for an image. I suggest using [http://images.google.com/ Google Images] to find some<br />
example images to try out. There should be a submit button and if the user clicks the submit button without putting something in the textbox<br />
they should get an error message.<br />
<br />
If the user has filled out the textbox, when they click the submit button a new image should be created and added to the page. You can create a<br />
placeholder '''div''' tag that will hold all of the images. After the image is added, it should be animated so that it shrinks down to a smaller size.<br />
<br />
''If you have a different idea for a jQuery assignment that uses a form, adds elements to the page based on the form and animates them once they are added, please email me. If it meets the requirements you can do something else that's more interesting to you.''<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_7&diff=17794Introduction to JavaScript Fall 2010 Class 72010-10-19T22:48:44Z<p>Matthew.ephraim: Created page with 'Back to Introduction to JavaScript Fall 2010 == Introduction == So far, I've shown you how to handle a user's interactions with page. Y…'</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
So far, I've shown you how to handle a user's interactions with page. You've seen how to handle user events like '''click''' and '''mouseover'''.<br />
And you've seen how you can use jQuery to modify elements on the page. One thing I haven't shown you, however, is how you can let a user add<br />
new elements to the page.<br />
<br />
This week, I will show you how you can read in values from form elements on the page and how you can use user entered data to<br />
allow a user to modify page elements.<br />
<br />
== HTML Forms ==<br />
<br />
The HTML form tag allow users to enter information and submit that information to a server. With JavaScript, you can also do thing with the<br />
information that a user entered.<br />
<br />
=== Getting the Values From a Form ===<br />
<br />
If you want to get the value of an input element, you'll need to find the element first. Then, once you've found the<br />
input element, you can use the [http://docs.jquery.com/Val '''val'''] function to get the value of the element.<br />
<br />
Let's say I have a form that looks like this:<br />
<br />
<form><br />
<input id="first-name" name="first-name" /><br />
<input id="last-name" name="last-name" /><br />
</form><br />
<br />
If I want to get the value of the '''first-name''' input, I can get to it like this:<br />
<br />
var firstNameField = $('#first-name');<br />
var firstName = firstNameField.val();<br />
<br />
Similarly, I can get to the last name input value like this:<br />
<br />
var lastNameField = $('#last-name');<br />
var lastName = lastNameField.val();<br />
<br />
In both cases, I'm simply finding the element and pulling the value out of it with '''val'''.<br />
<br />
Also, remember that you can always use the shorthand version of the above code like this:<br />
<br />
var firstName = $('#first-name').val();<br />
var lastName = $('#last-name').val();<br />
<br />
Both ways of finding the value are valid. Many people prefer the second method because it's shorter.<br />
<br />
=== Triming Whitespace ===<br />
<br />
Sometimes, you may need to make sure that you're not getting any extra information that you don't want from an input. For example,<br />
a user might accidentally put a space at the end of the value they entered in a textbox. You probably don't want that extra space, but, by default<br />
JavaScript will include it. So, if a user enters '''"Matthew "''' in the textbox, you'll get that extra space at the end.<br />
<br />
jQuery includes a function called [http://docs.jquery.com/Utilities/jQuery.trim trim] to get rid of any extra whitespace at the beginning or end of a string:<br />
<br />
var lastName = $('#last-name').val();<br />
var lastNameTrimmed = $.trim(lastName);<br />
<br />
In the example above, if the '''last-name''' input has any extra whitespace at the beginning or the end, the '''trim''' function will get rid of it.<br />
<br />
== Adding New Elements to the Page ==<br />
<br />
jQuery allows you to update an element's html by using the '''html''' function:<br />
<br />
var element = $('#my-element');<br />
<br />
// Change an element's html to "Some new text"<br />
element.html("Some new text");<br />
<br />
This works fine, but sometimes you want to do things that are a little bit more complicated.<br />
Let's say that you had an unordered list of items on the page and you wanted to use JavaScript to<br />
add a new item to the list. Using the html function, the only way you could do that would be to modify the HTML inside of the list:<br />
<br />
'''// DON'T DO THIS!!!!!'''<br />
var listHTML = $('#my-list').html();<br />
listHTML = listHTML + &quot;&lt;li&gt;New List Item&lt;/li&gt;&quot;;<br />
$('#my-list').html(listHTML);<br />
'''// DON'T DO THIS!!!!!'''<br />
<br />
Doing things this way works, but does it's not very flexible or pretty. jQuery offers a better way.<br />
<br />
=== Creating Elements With jQuery ===<br />
<br />
So far, we've been using jQuery to select items on the page using their tag names, ids or css classes. That's not all you can<br />
do with jQuery though. You can also use jQuery to create new elements for your page. To do this, you simply need to pass<br />
a string of HTML to the jQuery function. jQuery will take the string of HTML and create a new element with it:<br />
<br />
var newListItem = $('&lt;li&gt;My new list item&lt;/li&gt;');<br />
<br />
The variable called '''newListItem''' is now set to a list item element that says ''My new list item'' inside of it. The next step<br />
is actually adding the element to the page<br />
<br />
=== Adding Elements to the Page ===<br />
<br />
jQuery offers a number of ways to add elements to your page. We will cover a few simple ones today.<br />
<br />
Suppose there's an unordered list that already has two items in it:<br />
<br />
&lt;ul id=&quot;my-list&quot;&gt;<br />
&lt;li&gt;Item 1&lt;/li&gt;<br />
&lt;li&gt;Item 2&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
Above, I created a new element called '''myListItem'''. If I want to add it to the end of '''my-list''' I can use jQuery to find the<br />
list and then use the [http://docs.jquery.com/Manipulation/append '''append'''] function to add the list item to the end:<br />
<br />
var newListItem = $('&lt;li&gt;My new list item&lt;/li&gt;');<br />
var list = $('#my-list');<br />
<br />
list.append(newListItem);<br />
<br />
I can even shorten it up a little bit:<br />
<br />
$('#my-list').append($('&lt;li&gt;My new list item&lt;/li&gt;'));<br />
<br />
Similarly, if I want to add the new list item to the beginning of the list, before all of the other list items, I can use the<br />
[http://docs.jquery.com/Manipulation/prepend '''prepend'''] function:<br />
<br />
jQuery('#my-list').prepend(jQuery('&lt;li&gt;My new list item&lt;/li&gt;'));<br />
<br />
jQuery's '''append''' and '''prepend''' functions will both take one element and modify it by adding a new element to it. This gives you the same<br />
result as modifying the element's HTML, but also gives you more flexibility. Any new element that you create with jQuery can also be modified by<br />
jQuery, which includes adding class names, new attributes and event handlers.<br />
<br />
== Functions that Return Things ==<br />
<br />
Early in the class we talked a little bit about how you can create functions and how you can return things from those functions, but, so far,<br />
we haven't created our own functions that return a value.<br />
<br />
JavaScript functions are useful for encapsulating pieces of code that you want to run. Sometimes that code needs to send something back to <br />
the original code that called the function. The '''return''' keyword allows you to return one value back from the function.<br />
<br />
Today's activity involves checking a form to make sure that all of the elements are filled out. A useful function for the activity might<br />
be a function that returns '''true''' if all of the fields are filled out and returns '''false''' if any of the fields are empty. The<br />
basic structure of that function would look like this:<br />
<br />
function allFilledOut() {<br />
if (all of the fields are filled out) {<br />
return true;<br />
} else {<br />
return false;<br />
}<br />
}<br />
<br />
This code, of course, doesn't do anything yet because the if statement isn't actual code. However, the important part is the structure. I'm checking<br />
to make sure that all of the fields are filled out. If that statement turns out to be true, then the function returns '''true'''. Otherwise, the function<br />
returns false. Later, if I wanted to use the new '''allFilledOut''' function, I could call it in another piece of code and use the value that was returned:<br />
<br />
var '''completed''' = '''allFilledOut'''();<br />
if ('''completed''') {<br />
alert('The form is complete!');<br />
} else {<br />
alert('You still have things to fill out!')';<br />
}<br />
<br />
There are a few things to notice here. One is that I'm storing the '''return value''' of the '''allFilledOut''' function in a variable called '''completed'''.<br />
So, this variable will either be '''true''' or '''false''' after the function runs. Do I really need to create this variable though? Notice that I've also<br />
named my function '''allFilledOut'''. It might make sense to just put a call to that function right in my if statement like this:<br />
<br />
if ('''allFilledOut'''()) {<br />
alert('The form is complete!');<br />
} else {<br />
alert('You still have things to fill out!')';<br />
}<br />
<br />
Now the if statement looks more like a statement in English: ''if all of the fields are filled out then do one thing, or else do the other thing''. When you're<br />
creating functions that return true or false, it helps to name the functions in a way that makes your code read like you might write it out in regular English.<br />
<br />
Functions don't have to only return true and false values though. You can also use them return anything. For example, I might want a function that takes in a<br />
list of words and returns them as one string, separated by commas:<br />
<br />
function makeList(wordOne, wordTwo, wordThree) {<br />
var list = wordOne + ", " + wordTwo + ", " + wordThree;<br />
return list;<br />
}<br />
<br />
// Food should equal "pizza, burgers, popcorn"<br />
var food = makeSentence('pizza', 'burgers', 'popcorn'); <br />
<br />
The function called '''makeList''' takes in 3 parameters and builds a string that has all three parameters joined together as a list.<br />
<br />
== Activity 1 ==<br />
<br />
For tonight's activity, we will be creating a page that has a form that allows you add new messages to a page. There are two JavaScript files<br />
associated with this activity. The first one, called '''validation.js''', will handle validating the form field. In this case, if a form field<br />
has a class of '''required''' on it, the field will need to be filled out before the message can be added. If the user leaves any fields blank,<br />
they should get an error message and the required fields that were left blank should get a class called '''error''' added to them.<br />
<br />
The second JavaScript file, called '''messages.js''' will add new messages to the list on the right.<br />
<br />
The template for tonight's activity can be found [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_7/messages.zip here].<br />
<br />
== Assignment 4 ==<br />
<br />
'''Due Friday October 29th at 10pm '''<br />
<br />
So far, I've given you a template for each of your assignments. For this assignment, I want you to come up with a page and some JavaScript code that <br />
goes with the page on your own.<br />
<br />
Your page needs to have a textbox that will take in the url for an image. I suggest using [http://images.google.com/ Google Images] to find some<br />
example images to try out. There should be a submit button and if the user clicks the submit button without putting something in the textbox<br />
they should get an error message.<br />
<br />
If the user has filled out the textbox, when they click the submit button a new image should be created and added to the page. You can create a<br />
placeholder '''div''' tag that will hold all of the images. After the image is added, it should be animated so that it shrinks down to a smaller size.<br />
<br />
''If you have a different idea for a jQuery assignment that uses a form, adds elements to the page based on the form and animates them once they are added, please email me. If it meets the requirements you can do something else that's more interesting to you.''<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17774Introduction to JavaScript Fall 20102010-10-12T23:32:34Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
* Class 6 (10/12/2010): [[Introduction_to_JavaScript_Fall_2010_Class_6|JavaScript Objects]]<br />
<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_6&diff=17773Introduction to JavaScript Fall 2010 Class 62010-10-12T23:22:15Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store<br />
related information under a single variable, and how you can organize your code better by storing related functions inside of objects.<br />
<br />
== JavaScript Objects ==<br />
<br />
One JavaScript feature that we haven't talked about is '''JavaScript Objects'''. jQuery uses JavaScript objects for a few<br />
functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery<br />
provides.<br />
<br />
Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables?<br />
Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some<br />
information about a person. I could create a variable for their first name, and their last name and their job title. Later on,<br />
I might want to create another variable for their hometown.<br />
<br />
var firstName = "Matt";<br />
var lastName = "Ephraim";<br />
var jobTitle = "Programmer";<br />
var hometown = "Cedar Falls";<br />
<br />
So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the<br />
information about a person. I can do exactly that using a JavaScript object.<br />
<br />
First, I need to create a new object. I can create a new object for a person like this:<br />
<br />
var person = '''{}''';<br />
<br />
''Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say '''{}''' in your code, JavaScript will create<br />
a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".''<br />
<br />
'''Note:''' Don't confuse the two curly brackets ('''{}''') with 2 straight brackets ('''[]''').<br />
<br />
* '''{}''' will create a new object<br />
* '''[]''' will create a new array.<br />
<br />
Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:<br />
<br />
var person = {};<br />
person'''.firstName = "Matt";'''<br />
person'''.lastName = "Ephraim";'''<br />
person'''.jobTitle = "Programmer";'''<br />
person'''.hometown = "Cedar Falls";'''<br />
<br />
Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information<br />
I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the<br />
piece of information back by using the same name that I used when I set the piece of information, like this:<br />
<br />
alert(person'''.firstName'''); // alerts "Matt"<br />
alert(person'''.lastName'''); // alerts "Ephraim"<br />
alert(person'''.jobTitle'''); // alerts "Programmer"<br />
alert(person'''.hometown'''); // alerts "Cedar Falls"<br />
<br />
''Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it.<br />
So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.''<br />
<br />
There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same<br />
time that I was creating the variable, like this:<br />
<br />
var person = {<br />
firstName: "Matt",<br />
lastName: "Ephraim",<br />
jobTitle: "Programmer",<br />
hometown: "Cedar Falls"<br />
};<br />
<br />
This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only<br />
difference is that each item is set inside of the brackets. To create a new item (or '''property''') I can add the name of the<br />
property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property<br />
has to be inside of the brackets.<br />
<br />
''You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away''<br />
<br />
Remember jQuery's '''animate''' function? The animate function takes in an object that represents the CSS values you'd like to set for the element<br />
that you're animating:<br />
<br />
var element = $("#my_element");<br />
element.animate('''{ width: "100px", height: "300px" }''', 100);<br />
<br />
In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.<br />
<br />
== Using Obects to Organize Your Code ==<br />
<br />
Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that<br />
had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that<br />
made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we<br />
needed a few different variables called '''COMBINATION''', or what if we needed 2 functions called '''reset'''? Both of these issues<br />
could be addressed by storing the code related to the lock in an object, instead of just using regular variables.<br />
<br />
To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object '''Lock''':<br />
<br />
var '''Lock''' = {};<br />
<br />
'''Lock''' is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the '''Lock'''<br />
object:<br />
<br />
var '''Lock''' = {};<br />
Lock.COMBINATION = '111';<br />
<br />
Later, the lock's combination can be referenced like so:<br />
<br />
alert(Lock.COMBINATION);<br />
<br />
We can also stored the '''unlocked''' variable as a property on the lock, as well:<br />
<br />
Lock.'''unlocked''' = false;<br />
<br />
Later, the value can be changed or checked:<br />
<br />
if(Lock.'''unlocked''') {<br />
// do something<br />
}<br />
<br />
Lock.unlocked = true;<br />
<br />
Now that we have the variables stored as properties on the '''Lock''' object, instead of just as regular variables, we could have other objects<br />
that had '''COMBINATION''' or '''unlocked''' properies and use them somewhere else in our code:<br />
<br />
var BikeLock = {};<br />
BikeLock.COMBINATION = "5555";<br />
BikeLock.unlocked = false;<br />
<br />
if (BikeLock.unlocked) {<br />
// ride the bike<br />
}<br />
<br />
One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like<br />
this:<br />
<br />
function reset() {<br />
// some code to reset the lock<br />
}<br />
<br />
JavaScript also lets you create functions like this:<br />
<br />
'''var reset = function()''' {<br />
// some code to reset the lock<br />
};<br />
<br />
Notice that we are now creating a variable called '''reset''' and storing a function in the variable. Instead of giving the function a name right away,<br />
you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will<br />
work the same. Whichever way you use, you always be able to call the function like this:<br />
<br />
reset();<br />
<br />
Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the '''reset''' function on the<br />
'''Lock''' object looks like this:<br />
<br />
Lock.reset = function() {<br />
// some code to reset the lock<br />
}<br />
<br />
Later, to call the function, you would say:<br />
<br />
Lock.reset();<br />
<br />
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a<br />
better way.<br />
<br />
== Today's Interesting JavaScript Sites ==<br />
<br />
Many JavaScript libraries are built to allow "plugins". Plugins extend a JavaScript library with new features that might not make sense for the main<br />
library, but could come in handy for some sites.<br />
<br />
Below are a few examples of plugins for the jQuery library.<br />
<br />
* [http://www.9lessons.info/2010/10/new-twitter-design-css-jquery.html New Twitter Interface jQuery plugin]<br />
* [http://webdev.stephband.info/parallax.html Parallax jQuery plugin]<br />
* [http://jqueryui.com/ jQueryUI]<br />
<br />
<br />
== Activity 1 ==<br />
<br />
The first activity today involves the same lock game that we worked on during [[Introduction to JavaScript Fall 2010 Class 4|Class 4]].<br />
You can find completed version of the game [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_6/lock_completed.zip here].<br />
<br />
For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will<br />
call this object '''Lock'''. You can get started by creating a '''Lock''' object at the beginning of your code:<br />
<br />
var Lock = {};<br />
<br />
Then, once you have the empty object, you can start adding variables and functions to it:<br />
<br />
// Store the combination on the lock<br />
Lock.COMBINATION = "111";<br />
<br />
// Store the reset function<br />
Lock.reset = function() {<br />
// code for the reset function<br />
}<br />
<br />
You should only need to store variables that might be useful for all of your functions on the '''Lock''' object. <br />
If you're creating a variable inside of a function, don't worry about storing it on the '''Lock''' object. <br />
Just focus on variables like '''COMBINATION''' and '''unlocked''' that are declared outside of functions.<br />
<br />
<br />
== Activity 2 ==<br />
<br />
For this activity we're going to continue to rewrite the code for the lock using jQuery.<br />
<br />
I will walk you through each step and how you how jQuery can make things a little more streamlined.<br />
<br />
'''A few things to think about:'''<br />
<br />
* Selectors<br />
<br />
Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number<br />
boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:<br />
<br />
var numbers = jQuery('.number');<br />
<br />
You can then attach event handlers or modify styles using the '''numbers''' variable, which represents a collection of all of the number boxes that were found.<br />
<br />
* Adding classes<br />
<br />
You can add classes or remove classes for an element by using the '''addClass''' and '''removeClass''' functions:<br />
<br />
var element = jQuery('#id');<br />
element.addClass('highlighted');<br />
element.removeClass('highlighted');<br />
<br />
== Assignment 3 ==<br />
<br />
'''Remember that assignment 3 is due this Friday, October 15th'''<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_6&diff=17772Introduction to JavaScript Fall 2010 Class 62010-10-12T21:51:59Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store<br />
related information under a single variable, and how you can organize your code better by storing related functions inside of objects.<br />
<br />
== JavaScript Objects ==<br />
<br />
One JavaScript feature that we haven't talked about is '''JavaScript Objects'''. jQuery uses JavaScript objects for a few<br />
functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery<br />
provides.<br />
<br />
Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables?<br />
Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some<br />
information about a person. I could create a variable for their first name, and their last name and their job title. Later on,<br />
I might want to create another variable for their hometown.<br />
<br />
var firstName = "Matt";<br />
var lastName = "Ephraim";<br />
var jobTitle = "Programmer";<br />
var hometown = "Cedar Falls";<br />
<br />
So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the<br />
information about a person. I can do exactly that using a JavaScript object.<br />
<br />
First, I need to create a new object. I can create a new object for a person like this:<br />
<br />
var person = '''{}''';<br />
<br />
''Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say '''{}''' in your code, JavaScript will create<br />
a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".''<br />
<br />
'''Note:''' Don't confuse the two curly brackets ('''{}''') with 2 straight brackets ('''[]''').<br />
<br />
* '''{}''' will create a new object<br />
* '''[]''' will create a new array.<br />
<br />
Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:<br />
<br />
var person = {};<br />
person'''.firstName = "Matt";'''<br />
person'''.lastName = "Ephraim";'''<br />
person'''.jobTitle = "Programmer";'''<br />
person'''.hometown = "Cedar Falls";'''<br />
<br />
Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information<br />
I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the<br />
piece of information back by using the same name that I used when I set the piece of information, like this:<br />
<br />
alert(person'''.firstName'''); // alerts "Matt"<br />
alert(person'''.lastName'''); // alerts "Ephraim"<br />
alert(person'''.jobTitle'''); // alerts "Programmer"<br />
alert(person'''.hometown'''); // alerts "Cedar Falls"<br />
<br />
''Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it.<br />
So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.''<br />
<br />
There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same<br />
time that I was creating the variable, like this:<br />
<br />
var person = {<br />
firstName: "Matt",<br />
lastName: "Ephraim",<br />
jobTitle: "Programmer",<br />
hometown: "Cedar Falls"<br />
};<br />
<br />
This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only<br />
difference is that each item is set inside of the brackets. To create a new item (or '''property''') I can add the name of the<br />
property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property<br />
has to be inside of the brackets.<br />
<br />
''You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away''<br />
<br />
Remember jQuery's '''animate''' function? The animate function takes in an object that represents the CSS values you'd like to set for the element<br />
that you're animating:<br />
<br />
var element = $("#my_element");<br />
element.animate('''{ width: "100px", height: "300px" }''', 100);<br />
<br />
In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.<br />
<br />
== Using Obects to Organize Your Code ==<br />
<br />
Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that<br />
had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that<br />
made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we<br />
needed a few different variables called '''COMBINATION''', or what if we needed 2 functions called '''reset'''? Both of these issues<br />
could be addressed by storing the code related to the lock in an object, instead of just using regular variables.<br />
<br />
To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object '''Lock''':<br />
<br />
var '''Lock''' = {};<br />
<br />
'''Lock''' is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the '''Lock'''<br />
object:<br />
<br />
var '''Lock''' = {};<br />
Lock.COMBINATION = '111';<br />
<br />
Later, the lock's combination can be referenced like so:<br />
<br />
alert(Lock.COMBINATION);<br />
<br />
We can also stored the '''unlocked''' variable as a property on the lock, as well:<br />
<br />
Lock.'''unlocked''' = false;<br />
<br />
Later, the value can be changed or checked:<br />
<br />
if(Lock.'''unlocked''') {<br />
// do something<br />
}<br />
<br />
Lock.unlocked = true;<br />
<br />
Now that we have the variables stored as properties on the '''Lock''' object, instead of just as regular variables, we could have other objects<br />
that had '''COMBINATION''' or '''unlocked''' properies and use them somewhere else in our code:<br />
<br />
var BikeLock = {};<br />
BikeLock.COMBINATION = "5555";<br />
BikeLock.unlocked = false;<br />
<br />
if (BikeLock.unlocked) {<br />
// ride the bike<br />
}<br />
<br />
One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like<br />
this:<br />
<br />
function reset() {<br />
// some code to reset the lock<br />
}<br />
<br />
JavaScript also lets you create functions like this:<br />
<br />
'''var reset = function()''' {<br />
// some code to reset the lock<br />
};<br />
<br />
Notice that we are now creating a variable called '''reset''' and storing a function in the variable. Instead of giving the function a name right away,<br />
you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will<br />
work the same. Whichever way you use, you always be able to call the function like this:<br />
<br />
reset();<br />
<br />
Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the '''reset''' function on the<br />
'''Lock''' object looks like this:<br />
<br />
Lock.reset = function() {<br />
// some code to reset the lock<br />
}<br />
<br />
Later, to call the function, you would say:<br />
<br />
Lock.reset();<br />
<br />
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a<br />
better way.<br />
<br />
== Activity 1 ==<br />
<br />
The first activity today involves the same lock game that we worked on during [[Introduction to JavaScript Fall 2010 Class 4|Class 4]].<br />
You can find completed version of the game [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_6/lock_completed.zip here].<br />
<br />
For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will<br />
call this object '''Lock'''. You can get started by creating a '''Lock''' object at the beginning of your code:<br />
<br />
var Lock = {};<br />
<br />
Then, once you have the empty object, you can start adding variables and functions to it:<br />
<br />
// Store the combination on the lock<br />
Lock.COMBINATION = "111";<br />
<br />
// Store the reset function<br />
Lock.reset = function() {<br />
// code for the reset function<br />
}<br />
<br />
You should only need to store variables that might be useful for all of your functions on the '''Lock''' object. <br />
If you're creating a variable inside of a function, don't worry about storing it on the '''Lock''' object. <br />
Just focus on variables like '''COMBINATION''' and '''unlocked''' that are declared outside of functions.<br />
<br />
<br />
== Activity 2 ==<br />
<br />
For this activity we're going to continue to rewrite the code for the lock using jQuery.<br />
<br />
I will walk you through each step and how you how jQuery can make things a little more streamlined.<br />
<br />
'''A few things to think about:'''<br />
<br />
* Selectors<br />
<br />
Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number<br />
boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:<br />
<br />
var numbers = jQuery('.number');<br />
<br />
You can then attach event handlers or modify styles using the '''numbers''' variable, which represents a collection of all of the number boxes that were found.<br />
<br />
* Adding classes<br />
<br />
You can add classes or remove classes for an element by using the '''addClass''' and '''removeClass''' functions:<br />
<br />
var element = jQuery('#id');<br />
element.addClass('highlighted');<br />
element.removeClass('highlighted');<br />
<br />
== Assignment 3 ==<br />
<br />
'''Remember that assignment 3 is due this Friday, October 15th'''<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_6&diff=17771Introduction to JavaScript Fall 2010 Class 62010-10-12T21:50:59Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store<br />
related information under a single variable, and how you can organize your code better by storing related functions inside of objects.<br />
<br />
== JavaScript Objects ==<br />
<br />
One JavaScript feature that we haven't talked about is '''JavaScript Objects'''. jQuery uses JavaScript objects for a few<br />
functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery<br />
provides.<br />
<br />
Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables?<br />
Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some<br />
information about a person. I could create a variable for their first name, and their last name and their job title. Later on,<br />
I might want to create another variable for their hometown.<br />
<br />
var firstName = "Matt";<br />
var lastName = "Ephraim";<br />
var jobTitle = "Programmer";<br />
var hometown = "Cedar Falls";<br />
<br />
So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the<br />
information about a person. I can do exactly that using a JavaScript object.<br />
<br />
First, I need to create a new object. I can create a new object for a person like this:<br />
<br />
var person = '''{}''';<br />
<br />
''Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say '''{}''' in your code, JavaScript will create<br />
a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".''<br />
<br />
'''Note:''' Don't confuse the two curly brackets ('''{}''') with 2 straight brackets ('''[]''').<br />
<br />
* '''{}''' will create a new object<br />
* '''[]''' will create a new array.<br />
<br />
Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:<br />
<br />
var person = {};<br />
person'''.firstName = "Matt";'''<br />
person'''.lastName = "Ephraim";'''<br />
person'''.jobTitle = "Programmer";'''<br />
person'''.hometown = "Cedar Falls";'''<br />
<br />
Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information<br />
I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the<br />
piece of information back by using the same name that I used when I set the piece of information, like this:<br />
<br />
alert(person'''.firstName'''); // alerts "Matt"<br />
alert(person'''.lastName'''); // alerts "Ephraim"<br />
alert(person'''.jobTitle'''); // alerts "Programmer"<br />
alert(person'''.hometown'''); // alerts "Cedar Falls"<br />
<br />
''Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it.<br />
So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.''<br />
<br />
There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same<br />
time that I was creating the variable, like this:<br />
<br />
var person = {<br />
firstName: "Matt",<br />
lastName: "Ephraim",<br />
jobTitle: "Programmer",<br />
hometown: "Cedar Falls"<br />
};<br />
<br />
This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only<br />
difference is that each item is set inside of the brackets. To create a new item (or '''property''') I can add the name of the<br />
property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property<br />
has to be inside of the brackets.<br />
<br />
''You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away''<br />
<br />
Remember jQuery's '''animate''' function? The animate function takes in an object that represents the CSS values you'd like to set for the element<br />
that you're animating:<br />
<br />
var element = $("#my_element");<br />
element.animate('''{ width: "100px", height: "300px" }''', 100);<br />
<br />
In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.<br />
<br />
== Using Obects to Organize Your Code ==<br />
<br />
Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that<br />
had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that<br />
made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we<br />
needed a few different variables called '''COMBINATION''', or what if we needed 2 functions called '''reset'''? Both of these issues<br />
could be addressed by storing the code related to the lock in an object, instead of just using regular variables.<br />
<br />
To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object '''Lock''':<br />
<br />
var '''Lock''' = {};<br />
<br />
'''Lock''' is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the '''Lock'''<br />
object:<br />
<br />
var '''Lock''' = {};<br />
Lock.COMBINATION = '111';<br />
<br />
Later, the lock's combination can be referenced like so:<br />
<br />
alert(Lock.COMBINATION);<br />
<br />
We can also stored the '''unlocked''' variable as a property on the lock, as well:<br />
<br />
Lock.'''unlocked''' = false;<br />
<br />
Later, the value can be changed or checked:<br />
<br />
if(Lock.'''unlocked''') {<br />
// do something<br />
}<br />
<br />
Lock.unlocked = true;<br />
<br />
Now that we have the variables stored as properties on the '''Lock''' object, instead of just as regular variables, we could have other objects<br />
that had '''COMBINATION''' or '''unlocked''' properies and use them somewhere else in our code:<br />
<br />
var BikeLock = {};<br />
BikeLock.COMBINATION = "5555";<br />
BikeLock.unlocked = false;<br />
<br />
if (BikeLock.unlocked) {<br />
// ride the bike<br />
}<br />
<br />
One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like<br />
this:<br />
<br />
function reset() {<br />
// some code to reset the lock<br />
}<br />
<br />
JavaScript also lets you create functions like this:<br />
<br />
'''var reset = function()''' {<br />
// some code to reset the lock<br />
};<br />
<br />
Notice that we are now creating a variable called '''reset''' and storing a function in the variable. Instead of giving the function a name right away,<br />
you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will<br />
work the same. Whichever way you use, you always be able to call the function like this:<br />
<br />
reset();<br />
<br />
Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the '''reset''' function on the<br />
'''Lock''' object looks like this:<br />
<br />
Lock.reset = function() {<br />
// some code to reset the lock<br />
}<br />
<br />
Later, to call the function, you would say:<br />
<br />
Lock.reset();<br />
<br />
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a<br />
better way.<br />
<br />
== Activity 1 ==<br />
<br />
The first activity today involves the same lock game that we worked on during [[Introduction to JavaScript Fall 2010 Class 4|Class 4]].<br />
You can find completed version of the game [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_6/lock_completed.zip here].<br />
<br />
For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will<br />
call this object '''Lock'''. You can get started by creating a '''Lock''' object at the beginning of your code:<br />
<br />
var Lock = {};<br />
<br />
Then, once you have the empty object, you can start adding variables and functions to it:<br />
<br />
// Store the combination on the lock<br />
Lock.COMBINATION = "111";<br />
<br />
// Store the reset function<br />
Lock.reset = function() {<br />
// code for the reset function<br />
}<br />
<br />
You should only need to store variables that might be useful for all of your functions on the '''Lock''' object. <br />
If you're creating a variable inside of a function, don't worry about storing it on the '''Lock''' object. <br />
Just focus on variables like '''COMBINATION''' and '''unlocked''' that are declared outside of functions.<br />
<br />
<br />
== Activity 2 ==<br />
<br />
For this activity we're going to continue to rewrite the code for the lock using jQuery.<br />
<br />
I will walk you through each step and how you how jQuery can make things a little more streamlined.<br />
<br />
'''A few things to think about:'''<br />
<br />
* Selectors<br />
<br />
Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number<br />
boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:<br />
<br />
var numbers = jQuery('.number');<br />
<br />
You can then attach event handlers or modify styles using the '''numbers''' variable, which represents a collection of all of the number boxes that were found.<br />
<br />
* Adding classes<br />
<br />
You can add classes or remove classes for an element by using the '''addClass''' and '''removeClass''' functions:<br />
<br />
var element = jQuery('#id');<br />
element.addClass('highlighted');<br />
element.removeClass('highlighted');<br />
<br />
== Assignment 3 ==<br />
<br />
'''Remember that assignment 3 is due this Friday, October 15th'''</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_6&diff=17770Introduction to JavaScript Fall 2010 Class 62010-10-12T21:50:03Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store<br />
related information under a single variable, and how you can organize your code better by storing related functions inside of objects.<br />
<br />
== JavaScript Objects ==<br />
<br />
One JavaScript feature that we haven't talked about is '''JavaScript Objects'''. jQuery uses JavaScript objects for a few<br />
functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery<br />
provides.<br />
<br />
Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables?<br />
Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some<br />
information about a person. I could create a variable for their first name, and their last name and their job title. Later on,<br />
I might want to create another variable for their hometown.<br />
<br />
var firstName = "Matt";<br />
var lastName = "Ephraim";<br />
var jobTitle = "Programmer";<br />
var hometown = "Cedar Falls";<br />
<br />
So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the<br />
information about a person. I can do exactly that using a JavaScript object.<br />
<br />
First, I need to create a new object. I can create a new object for a person like this:<br />
<br />
var person = '''{}''';<br />
<br />
''Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say '''{}''' in your code, JavaScript will create<br />
a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".''<br />
<br />
'''Note:''' Don't confuse the two curly brackets ('''{}''') with 2 straight brackets ('''[]''').<br />
<br />
* '''{}''' will create a new object<br />
* '''[]''' will create a new array.<br />
<br />
Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:<br />
<br />
var person = {};<br />
person'''.firstName = "Matt";'''<br />
person'''.lastName = "Ephraim";'''<br />
person'''.jobTitle = "Programmer";'''<br />
person'''.hometown = "Cedar Falls";'''<br />
<br />
Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information<br />
I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the<br />
piece of information back by using the same name that I used when I set the piece of information, like this:<br />
<br />
alert(person'''.firstName'''); // alerts "Matt"<br />
alert(person'''.lastName'''); // alerts "Ephraim"<br />
alert(person'''.jobTitle'''); // alerts "Programmer"<br />
alert(person'''.hometown'''); // alerts "Cedar Falls"<br />
<br />
''Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it.<br />
So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.''<br />
<br />
There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same<br />
time that I was creating the variable, like this:<br />
<br />
var person = {<br />
firstName: "Matt",<br />
lastName: "Ephraim",<br />
jobTitle: "Programmer",<br />
hometown: "Cedar Falls"<br />
};<br />
<br />
This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only<br />
difference is that each item is set inside of the brackets. To create a new item (or '''property''') I can add the name of the<br />
property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property<br />
has to be inside of the brackets.<br />
<br />
''You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away''<br />
<br />
Remember jQuery's '''animate''' function? The animate function takes in an object that represents the CSS values you'd like to set for the element<br />
that you're animating:<br />
<br />
var element = $("#my_element");<br />
element.animate('''{ width: "100px", height: "300px" }''', 100);<br />
<br />
In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.<br />
<br />
== Using Obects to Organize Your Code ==<br />
<br />
Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that<br />
had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that<br />
made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we<br />
needed a few different variables called '''COMBINATION''', or what if we needed 2 functions called '''reset'''? Both of these issues<br />
could be addressed by storing the code related to the lock in an object, instead of just using regular variables.<br />
<br />
To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object '''Lock''':<br />
<br />
var '''Lock''' = {};<br />
<br />
'''Lock''' is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the '''Lock'''<br />
object:<br />
<br />
var '''Lock''' = {};<br />
Lock.COMBINATION = '111';<br />
<br />
Later, the lock's combination can be referenced like so:<br />
<br />
alert(Lock.COMBINATION);<br />
<br />
We can also stored the '''unlocked''' variable as a property on the lock, as well:<br />
<br />
Lock.'''unlocked''' = false;<br />
<br />
Later, the value can be changed or checked:<br />
<br />
if(Lock.'''unlocked''') {<br />
// do something<br />
}<br />
<br />
Lock.unlocked = true;<br />
<br />
Now that we have the variables stored as properties on the '''Lock''' object, instead of just as regular variables, we could have other objects<br />
that had '''COMBINATION''' or '''unlocked''' properies and use them somewhere else in our code:<br />
<br />
var BikeLock = {};<br />
BikeLock.COMBINATION = "5555";<br />
BikeLock.unlocked = false;<br />
<br />
if (BikeLock.unlocked) {<br />
// ride the bike<br />
}<br />
<br />
One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like<br />
this:<br />
<br />
function reset() {<br />
// some code to reset the lock<br />
}<br />
<br />
JavaScript also lets you create functions like this:<br />
<br />
'''var reset = function()''' {<br />
// some code to reset the lock<br />
};<br />
<br />
Notice that we are now creating a variable called '''reset''' and storing a function in the variable. Instead of giving the function a name right away,<br />
you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will<br />
work the same. Whichever way you use, you always be able to call the function like this:<br />
<br />
reset();<br />
<br />
Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the '''reset''' function on the<br />
'''Lock''' object looks like this:<br />
<br />
Lock.reset = function() {<br />
// some code to reset the lock<br />
}<br />
<br />
Later, to call the function, you would say:<br />
<br />
Lock.reset();<br />
<br />
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a<br />
better way.<br />
<br />
== Activity 1 ==<br />
<br />
The first activity today involves the same lock game that we worked on during [[Introduction to JavaScript Fall 2010 Class 4|Class 4]].<br />
You can find completed version of the game [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_6/lock_completed.zip here].<br />
<br />
For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will<br />
call this object '''Lock'''. You can get started by creating a '''Lock''' object at the beginning of your code:<br />
<br />
var Lock = {};<br />
<br />
Then, once you have the empty object, you can start adding variables and functions to it:<br />
<br />
// Store the combination on the lock<br />
Lock.COMBINATION = "111";<br />
<br />
// Store the reset function<br />
Lock.reset = function() {<br />
// code for the reset function<br />
}<br />
<br />
You should only need to store variables that might be useful for all of your functions on the '''Lock''' object. <br />
If you're creating a variable inside of a function, don't worry about storing it on the '''Lock''' object. <br />
Just focus on variables like '''COMBINATION''' and '''unlocked''' that are declared outside of functions.<br />
<br />
<br />
== Activity 2 ==<br />
<br />
For this activity we're going to continue to rewrite the code for the lock using jQuery.<br />
<br />
I will walk you through each step and how you how jQuery can make things a little more streamlined.<br />
You may also want to look at the [http://www.mattephraim.com/intro_to_javascript/class_7/lock_solution.js solution for the orignal] lock as reference.<br />
<br />
'''A few things to think about:'''<br />
<br />
* Selectors<br />
<br />
Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number<br />
boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:<br />
<br />
var numbers = jQuery('.number');<br />
<br />
You can then attach event handlers or modify styles using the '''numbers''' variable, which represents a collection of all of the number boxes that were found.<br />
<br />
* Adding classes<br />
<br />
You can add classes or remove classes for an element by using the '''addClass''' and '''removeClass''' functions:<br />
<br />
var element = jQuery('#id');<br />
element.addClass('highlighted');<br />
element.removeClass('highlighted');<br />
<br />
== Assignment 3 ==<br />
<br />
'''Remember that assignment 3 is due this Friday, October 15th'''</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_6&diff=17769Introduction to JavaScript Fall 2010 Class 62010-10-12T21:49:32Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store<br />
related information under a single variable, and how you can organize your code better by storing related functions inside of objects.<br />
<br />
== JavaScript Objects ==<br />
<br />
One JavaScript feature that we haven't talked about is '''JavaScript Objects'''. jQuery uses JavaScript objects for a few<br />
functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery<br />
provides.<br />
<br />
Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables?<br />
Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some<br />
information about a person. I could create a variable for their first name, and their last name and their job title. Later on,<br />
I might want to create another variable for their hometown.<br />
<br />
var firstName = "Matt";<br />
var lastName = "Ephraim";<br />
var jobTitle = "Programmer";<br />
var hometown = "Cedar Falls";<br />
<br />
So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the<br />
information about a person. I can do exactly that using a JavaScript object.<br />
<br />
First, I need to create a new object. I can create a new object for a person like this:<br />
<br />
var person = '''{}''';<br />
<br />
''Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say '''{}''' in your code, JavaScript will create<br />
a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".''<br />
<br />
'''Note:''' Don't confuse the two curly brackets ('''{}''') with 2 straight brackets ('''[]''').<br />
<br />
* '''{}''' will create a new object<br />
* '''[]''' will create a new array.<br />
<br />
Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:<br />
<br />
var person = {};<br />
person'''.firstName = "Matt";'''<br />
person'''.lastName = "Ephraim";'''<br />
person'''.jobTitle = "Programmer";'''<br />
person'''.hometown = "Cedar Falls";'''<br />
<br />
Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information<br />
I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the<br />
piece of information back by using the same name that I used when I set the piece of information, like this:<br />
<br />
alert(person'''.firstName'''); // alerts "Matt"<br />
alert(person'''.lastName'''); // alerts "Ephraim"<br />
alert(person'''.jobTitle'''); // alerts "Programmer"<br />
alert(person'''.hometown'''); // alerts "Cedar Falls"<br />
<br />
''Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it.<br />
So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.''<br />
<br />
There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same<br />
time that I was creating the variable, like this:<br />
<br />
var person = {<br />
firstName: "Matt",<br />
lastName: "Ephraim",<br />
jobTitle: "Programmer",<br />
hometown: "Cedar Falls"<br />
};<br />
<br />
This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only<br />
difference is that each item is set inside of the brackets. To create a new item (or '''property''') I can add the name of the<br />
property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property<br />
has to be inside of the brackets.<br />
<br />
''You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away''<br />
<br />
Remember jQuery's '''animate''' function? The animate function takes in an object that represents the CSS values you'd like to set for the element<br />
that you're animating:<br />
<br />
var element = $("#my_element");<br />
element.animate('''{ width: "100px", height: "300px" }''', 100);<br />
<br />
In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.<br />
<br />
== Using Obects to Organize Your Code ==<br />
<br />
Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that<br />
had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that<br />
made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we<br />
needed a few different variables called '''COMBINATION''', or what if we needed 2 functions called '''reset'''? Both of these issues<br />
could be addressed by storing the code related to the lock in an object, instead of just using regular variables.<br />
<br />
To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object '''Lock''':<br />
<br />
var '''Lock''' = {};<br />
<br />
'''Lock''' is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the '''Lock'''<br />
object:<br />
<br />
var '''Lock''' = {};<br />
Lock.COMBINATION = '111';<br />
<br />
Later, the lock's combination can be referenced like so:<br />
<br />
alert(Lock.COMBINATION);<br />
<br />
We can also stored the '''unlocked''' variable as a property on the lock, as well:<br />
<br />
Lock.'''unlocked''' = false;<br />
<br />
Later, the value can be changed or checked:<br />
<br />
if(Lock.'''unlocked''') {<br />
// do something<br />
}<br />
<br />
Lock.unlocked = true;<br />
<br />
Now that we have the variables stored as properties on the '''Lock''' object, instead of just as regular variables, we could have other objects<br />
that had '''COMBINATION''' or '''unlocked''' properies and use them somewhere else in our code:<br />
<br />
var BikeLock = {};<br />
BikeLock.COMBINATION = "5555";<br />
BikeLock.unlocked = false;<br />
<br />
if (BikeLock.unlocked) {<br />
// ride the bike<br />
}<br />
<br />
One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like<br />
this:<br />
<br />
function reset() {<br />
// some code to reset the lock<br />
}<br />
<br />
JavaScript also lets you create functions like this:<br />
<br />
'''var reset = function()''' {<br />
// some code to reset the lock<br />
};<br />
<br />
Notice that we are now creating a variable called '''reset''' and storing a function in the variable. Instead of giving the function a name right away,<br />
you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will<br />
work the same. Whichever way you use, you always be able to call the function like this:<br />
<br />
reset();<br />
<br />
Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the '''reset''' function on the<br />
'''Lock''' object looks like this:<br />
<br />
Lock.reset = function() {<br />
// some code to reset the lock<br />
}<br />
<br />
Later, to call the function, you would say:<br />
<br />
Lock.reset();<br />
<br />
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a<br />
better way.<br />
<br />
== Activity 1 ==<br />
<br />
The first activity today involves the same lock game that we worked on during [[Introduction to JavaScript Fall 2010 Class 4|Class 4]].<br />
You can find completed version of the game [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_6/lock_completed.zip here].<br />
<br />
For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will<br />
call this object '''Lock'''. You can get started by creating a '''Lock''' object at the beginning of your code:<br />
<br />
var Lock = {};<br />
<br />
Then, once you have the empty object, you can start adding variables and functions to it:<br />
<br />
// Store the combination on the lock<br />
Lock.COMBINATION = "111";<br />
<br />
// Store the reset function<br />
Lock.reset = function() {<br />
// code for the reset function<br />
}<br />
<br />
You should only need to store variables that might be useful for all of your functions on the '''Lock''' object. <br />
If you're creating a variable inside of a function, don't worry about storing it on the '''Lock''' object. <br />
Just focus on variables like '''COMBINATION''' and '''unlocked''' that are declared outside of functions.<br />
<br />
<br />
== Activity 2 ==<br />
<br />
For this activity we're going to continue to rewrite the code for the lock and using jQuery.<br />
<br />
I will walk you through each step and how you how jQuery can make things a little more streamlined.<br />
You may also want to look at the [http://www.mattephraim.com/intro_to_javascript/class_7/lock_solution.js solution for the orignal] lock as reference.<br />
<br />
'''A few things to think about:'''<br />
<br />
* Selectors<br />
<br />
Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number<br />
boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:<br />
<br />
var numbers = jQuery('.number');<br />
<br />
You can then attach event handlers or modify styles using the '''numbers''' variable, which represents a collection of all of the number boxes that were found.<br />
<br />
* Adding classes<br />
<br />
You can add classes or remove classes for an element by using the '''addClass''' and '''removeClass''' functions:<br />
<br />
var element = jQuery('#id');<br />
element.addClass('highlighted');<br />
element.removeClass('highlighted');<br />
<br />
== Assignment 3 ==<br />
<br />
'''Remember that assignment 3 is due this Friday, October 15th'''</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_6&diff=17768Introduction to JavaScript Fall 2010 Class 62010-10-12T21:46:21Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store<br />
related information under a single variable, and how you can organize your code better by storing related functions inside of objects.<br />
<br />
== JavaScript Objects ==<br />
<br />
One JavaScript feature that we haven't talked about is '''JavaScript Objects'''. jQuery uses JavaScript objects for a few<br />
functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery<br />
provides.<br />
<br />
Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables?<br />
Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some<br />
information about a person. I could create a variable for their first name, and their last name and their job title. Later on,<br />
I might want to create another variable for their hometown.<br />
<br />
var firstName = "Matt";<br />
var lastName = "Ephraim";<br />
var jobTitle = "Programmer";<br />
var hometown = "Cedar Falls";<br />
<br />
So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the<br />
information about a person. I can do exactly that using a JavaScript object.<br />
<br />
First, I need to create a new object. I can create a new object for a person like this:<br />
<br />
var person = '''{}''';<br />
<br />
''Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say '''{}''' in your code, JavaScript will create<br />
a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".''<br />
<br />
'''Note:''' Don't confuse the two curly brackets ('''{}''') with 2 straight brackets ('''[]''').<br />
<br />
* '''{}''' will create a new object<br />
* '''[]''' will create a new array.<br />
<br />
Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:<br />
<br />
var person = {};<br />
person'''.firstName = "Matt";'''<br />
person'''.lastName = "Ephraim";'''<br />
person'''.jobTitle = "Programmer";'''<br />
person'''.hometown = "Cedar Falls";'''<br />
<br />
Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information<br />
I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the<br />
piece of information back by using the same name that I used when I set the piece of information, like this:<br />
<br />
alert(person'''.firstName'''); // alerts "Matt"<br />
alert(person'''.lastName'''); // alerts "Ephraim"<br />
alert(person'''.jobTitle'''); // alerts "Programmer"<br />
alert(person'''.hometown'''); // alerts "Cedar Falls"<br />
<br />
''Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it.<br />
So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.''<br />
<br />
There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same<br />
time that I was creating the variable, like this:<br />
<br />
var person = {<br />
firstName: "Matt",<br />
lastName: "Ephraim",<br />
jobTitle: "Programmer",<br />
hometown: "Cedar Falls"<br />
};<br />
<br />
This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only<br />
difference is that each item is set inside of the brackets. To create a new item (or '''property''') I can add the name of the<br />
property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property<br />
has to be inside of the brackets.<br />
<br />
''You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away''<br />
<br />
Remember jQuery's '''animate''' function? The animate function takes in an object that represents the CSS values you'd like to set for the element<br />
that you're animating:<br />
<br />
var element = $("#my_element");<br />
element.animate('''{ width: "100px", height: "300px" }''', 100);<br />
<br />
In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.<br />
<br />
== Using Obects to Organize Your Code ==<br />
<br />
Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that<br />
had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that<br />
made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we<br />
needed a few different variables called '''COMBINATION''', or what if we needed 2 functions called '''reset'''? Both of these issues<br />
could be addressed by storing the code related to the lock in an object, instead of just using regular variables.<br />
<br />
To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object '''Lock''':<br />
<br />
var '''Lock''' = {};<br />
<br />
'''Lock''' is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the '''Lock'''<br />
object:<br />
<br />
var '''Lock''' = {};<br />
Lock.COMBINATION = '111';<br />
<br />
Later, the lock's combination can be referenced like so:<br />
<br />
alert(Lock.COMBINATION);<br />
<br />
We can also stored the '''unlocked''' variable as a property on the lock, as well:<br />
<br />
Lock.'''unlocked''' = false;<br />
<br />
Later, the value can be changed or checked:<br />
<br />
if(Lock.'''unlocked''') {<br />
// do something<br />
}<br />
<br />
Lock.unlocked = true;<br />
<br />
Now that we have the variables stored as properties on the '''Lock''' object, instead of just as regular variables, we could have other objects<br />
that had '''COMBINATION''' or '''unlocked''' properies and use them somewhere else in our code:<br />
<br />
var BikeLock = {};<br />
BikeLock.COMBINATION = "5555";<br />
BikeLock.unlocked = false;<br />
<br />
if (BikeLock.unlocked) {<br />
// ride the bike<br />
}<br />
<br />
One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like<br />
this:<br />
<br />
function reset() {<br />
// some code to reset the lock<br />
}<br />
<br />
JavaScript also lets you create functions like this:<br />
<br />
'''var reset = function()''' {<br />
// some code to reset the lock<br />
};<br />
<br />
Notice that we are now creating a variable called '''reset''' and storing a function in the variable. Instead of giving the function a name right away,<br />
you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will<br />
work the same. Whichever way you use, you always be able to call the function like this:<br />
<br />
reset();<br />
<br />
Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the '''reset''' function on the<br />
'''Lock''' object looks like this:<br />
<br />
Lock.reset = function() {<br />
// some code to reset the lock<br />
}<br />
<br />
Later, to call the function, you would say:<br />
<br />
Lock.reset();<br />
<br />
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a<br />
better way.<br />
<br />
== Activity 1 ==<br />
<br />
The first activity today involves the same lock game that we worked on during [[Introduction to JavaScript Fall 2010 Class 4|Class 4]].<br />
You can find completed version of the game [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_6/lock_completed.zip here].<br />
<br />
For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will<br />
call this object '''Lock'''. You can get started by creating a '''Lock''' object at the beginning of your code:<br />
<br />
var Lock = {};<br />
<br />
Then, once you have the empty object, you can start adding variables and functions to it:<br />
<br />
// Store the combination on the lock<br />
Lock.COMBINATION = "111";<br />
<br />
// Store the reset function<br />
Lock.reset = function() {<br />
// code for the reset function<br />
}<br />
<br />
You should only need to store variables that might be useful for all of your functions on the '''Lock''' object. <br />
If you're creating a variable inside of a function, don't worry about storing it on the '''Lock''' object. <br />
Just focus on variables like '''COMBINATION''' and '''unlocked''' that are declared outside of functions.<br />
<br />
<br />
== Activity 2 ==<br />
<br />
For this activity we're going to rewrite the code for the lock and use jQuery.<br />
<br />
I will walk you through each step and how you how jQuery can make things a little more streamlined.<br />
You may also want to look at the [http://www.mattephraim.com/intro_to_javascript/class_7/lock_solution.js solution for the orignal] lock as reference.<br />
<br />
'''A few things to think about:'''<br />
<br />
* Selectors<br />
<br />
Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number<br />
boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:<br />
<br />
var numbers = jQuery('.number');<br />
<br />
You can then attach event handlers or modify styles using the '''numbers''' variable, which represents a collection of all of the number boxes that were found.<br />
<br />
* Adding classes<br />
<br />
You can add classes or remove classes for an element by using the '''addClass''' and '''removeClass''' functions:<br />
<br />
var element = jQuery('#id');<br />
element.addClass('highlighted');<br />
element.removeClass('highlighted');<br />
<br />
== Assignment 3 ==<br />
<br />
'''Remember that assignment 3 is due this Friday, October 15th'''</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_6&diff=17767Introduction to JavaScript Fall 2010 Class 62010-10-12T21:38:38Z<p>Matthew.ephraim: Created page with '== Introduction == This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store related information un…'</p>
<hr />
<div>== Introduction ==<br />
<br />
This week we will talk about JavaScript '''objects'''. Objects are useful for a few different things. I will show you how you can store<br />
related information under a single variable, and how you can organize your code better by storing related functions inside of objects.<br />
<br />
== JavaScript Objects ==<br />
<br />
One JavaScript feature that we haven't talked about is '''JavaScript Objects'''. jQuery uses JavaScript objects for a few<br />
functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery<br />
provides.<br />
<br />
Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables?<br />
Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some<br />
information about a person. I could create a variable for their first name, and their last name and their job title. Later on,<br />
I might want to create another variable for their hometown.<br />
<br />
var firstName = "Matt";<br />
var lastName = "Ephraim";<br />
var jobTitle = "Programmer";<br />
var hometown = "Cedar Falls";<br />
<br />
So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the<br />
information about a person. I can do exactly that using a JavaScript object.<br />
<br />
First, I need to create a new object. I can create a new object for a person like this:<br />
<br />
var person = '''{}''';<br />
<br />
''Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say '''{}''' in your code, JavaScript will create<br />
a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".''<br />
<br />
'''Note:''' Don't confuse the two curly brackets ('''{}''') with 2 straight brackets ('''[]''').<br />
<br />
* '''{}''' will create a new object<br />
* '''[]''' will create a new array.<br />
<br />
Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:<br />
<br />
var person = {};<br />
person'''.firstName = "Matt";'''<br />
person'''.lastName = "Ephraim";'''<br />
person'''.jobTitle = "Programmer";'''<br />
person'''.hometown = "Cedar Falls";'''<br />
<br />
Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information<br />
I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the<br />
piece of information back by using the same name that I used when I set the piece of information, like this:<br />
<br />
alert(person'''.firstName'''); // alerts "Matt"<br />
alert(person'''.lastName'''); // alerts "Ephraim"<br />
alert(person'''.jobTitle'''); // alerts "Programmer"<br />
alert(person'''.hometown'''); // alerts "Cedar Falls"<br />
<br />
''Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it.<br />
So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.''<br />
<br />
There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same<br />
time that I was creating the variable, like this:<br />
<br />
var person = {<br />
firstName: "Matt",<br />
lastName: "Ephraim",<br />
jobTitle: "Programmer",<br />
hometown: "Cedar Falls"<br />
};<br />
<br />
This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only<br />
difference is that the each item is set inside of the brackets. To create a new item (or '''property''') I can add the name of the<br />
property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property<br />
has to be inside of the brackets.<br />
<br />
''You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away''<br />
<br />
Remember jQuery's '''animate''' function? The animate function takes in an object that represents the CSS values you'd like to set for the element<br />
that you're animating:<br />
<br />
var element = $("#my_element");<br />
element.animate('''{ width: "100px", height: "300px" }''', 100);<br />
<br />
In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.<br />
<br />
== Using Obects to Organize Your Code ==<br />
<br />
Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that<br />
had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that<br />
made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we<br />
needed a few different variables called '''COMBINATION''', or what if we needed 2 functions called '''reset'''? Both of these issues<br />
could be addressed by storing the code related to the lock in an object, instead of just using regular variables.<br />
<br />
To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object '''Lock''':<br />
<br />
var '''Lock''' = {};<br />
<br />
'''Lock''' is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the '''Lock'''<br />
object:<br />
<br />
var '''Lock''' = {};<br />
Lock.COMBINATION = '111';<br />
<br />
Later, the lock's combination can be referenced like so:<br />
<br />
alert(Lock.COMBINATION);<br />
<br />
We can also stored the '''unlocked''' variable as a property on the lock, as well:<br />
<br />
Lock.'''unlocked''' = false;<br />
<br />
Later, the value can be changed or checked:<br />
<br />
if(Lock.'''unlocked''') {<br />
// do something<br />
}<br />
<br />
Lock.unlocked = true;<br />
<br />
Now that we have the variables stored as properties on the '''Lock''' object, instead of just as regular variables, we could have other objects<br />
that had '''COMBINATION''' or '''unlocked''' properies and use them somewhere else in our code:<br />
<br />
var BikeLock = {};<br />
BikeLock.COMBINATION = "5555";<br />
BikeLock.unlocked = false;<br />
<br />
if (BikeLock.unlocked) {<br />
// ride the bike<br />
}<br />
<br />
One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like<br />
this:<br />
<br />
function reset() {<br />
// some code to reset the lock<br />
}<br />
<br />
JavaScript also lets you create functions like this:<br />
<br />
'''var reset = function()''' {<br />
// some code to reset the lock<br />
};<br />
<br />
Notice that we are now creating a variable called '''reset''' and storing a function in the variable. Instead of giving the function a name right away,<br />
you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will<br />
work the same. Whichever way you use, you always be able to call the function like this:<br />
<br />
reset();<br />
<br />
Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the '''reset''' function on the<br />
'''Lock''' object looks like this:<br />
<br />
Lock.reset = function() {<br />
// some code to reset the lock<br />
}<br />
<br />
Later, to call the function, you would say:<br />
<br />
Lock.reset();<br />
<br />
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a<br />
better way.<br />
<br />
== Activity 1 ==<br />
<br />
The first activity today involves the same lock game that we worked on during [[Introduction to JavaScript Fall 2010 Class 4|Class 4]].<br />
You can find the template for the game [http://www.mattephraim.com/intro_to_javascript/class_7/game.zip here].<br />
<br />
For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will<br />
call this object '''Lock'''. You can get started by creating a '''Lock''' object at the beginning of your code:<br />
<br />
var Lock = {};<br />
<br />
Then, once you have the empty object, you can start adding variables and functions to it:<br />
<br />
// Store the combination on the lock<br />
Lock.COMBINATION = "111";<br />
<br />
// Store the reset function<br />
Lock.reset = function() {<br />
// code for the reset function<br />
}<br />
<br />
You should only need to store variables that might be useful for all of your functions on the '''Lock''' object. <br />
If you're creating a variable inside of a function, don't worry about storing it on the '''Lock''' object. <br />
Just focus on variables like '''COMBINATION''' and '''unlocked''' that are declared outside of functions.<br />
<br />
<br />
== Activity 2 ==<br />
<br />
For this activity we're going to rewrite the code for the lock and use jQuery.<br />
<br />
I will walk you through each step and how you how jQuery can make things a little more streamlined.<br />
You may also want to look at the [http://www.mattephraim.com/intro_to_javascript/class_7/lock_solution.js solution for the orignal] lock as reference.<br />
<br />
'''A few things to think about:'''<br />
<br />
* Selectors<br />
<br />
Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number<br />
boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:<br />
<br />
var numbers = jQuery('.number');<br />
<br />
You can then attach event handlers or modify styles using the '''numbers''' variable, which represents a collection of all of the number boxes that were found.<br />
<br />
* Adding classes<br />
<br />
You can add classes or remove classes for an element by using the '''addClass''' and '''removeClass''' functions:<br />
<br />
var element = jQuery('#id');<br />
element.addClass('highlighted');<br />
element.removeClass('highlighted');<br />
<br />
== Assignment 3 ==<br />
<br />
'''Remember that assignment 3 is due this Friday, October 15th'''</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_5&diff=17758Introduction to JavaScript Fall 2010 Class 52010-10-05T22:12:08Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
So far, we've been writing all of our JavaScript by hand. You may have noticed that some if it gets repetitive.<br />
Typing '''document.getElementById''' and giving all of the elements on your page ids might start to seem like<br />
a chore. Thankfully, there are ways to streamline the process of adding JavaScript to your page.<br />
<br />
One thing that you can do to speed up your JavaScript development is use a JavaScript library. '''JavaScript libraries'''<br />
are collections of handy functions and tools that have been written by other people. When you include<br />
a JavaScript library on your page you can take advantage of the functionality that other people have written.<br />
<br />
In this class, we will be mainly focusing on a library called [http://jquery.com jQuery]. jQuery is an open source<br />
library that provides utlities for adding JavaScript event handlers to page elements and for manipulating HTML elements<br />
using JavaScript.<br />
<br />
== A Word About CSS ==<br />
<br />
One important element that you will need to understand before using jQuery is Cascading Style Sheets (CSS). If you don't already know<br />
how to use CSS, here is a brief summary of the basic elements of CSS.<br />
<br />
As I have mentioned before in this class, CSS is used for styling the HTML elements of your page. CSS consists of selectors, which are used<br />
to target HTML elements on the page, and styles, which are used to style the elements that are being targeted.<br />
<br />
For example, the following piece of code targets elements that have the class name .callout, and gives them a blue border that is 3 pixels thick:<br />
<br />
.callout {<br />
border: 3px solid blue;<br />
}<br />
<br />
=== Selectors ===<br />
<br />
While CSS styles are important, you will first need to understand CSS selectors before you can use jQuery. Below are three different types of<br />
selectors that you will commonly see used with jQuery.<br />
<br />
'''Tag'''<br />
<br />
Tag selectors select a type of HTML tag. Each selector matches up with the name of the HTML tag you'd like to target. The following CSS targets all<br />
h3 tags and makes the text inside of them red:<br />
<br />
h3 {<br />
color: red;<br />
}<br />
<br />
'''ID'''<br />
<br />
ID selectors are used to target elements that have a particular ID. ID selectors consist of a pound sign ''(#)'' and the ID you'd like to target.<br />
ID's should be only used one time per page, so an ID selector will target a single item on the page. For example, you could target the element with<br />
an ID of "logo" like this:<br />
<br />
#logo {<br />
float: left;<br />
border: 1px solid blue;<br />
}<br />
<br />
'''Class'''<br />
<br />
Class selectors select all HTML tags of a particular class name. Class selectors consist of a dot ''(.)'' followed by the class name you'd like<br />
to target. So, for example, a CSS rule that targets all elements with a class name of "selected" looks like this:<br />
<br />
.selected {<br />
background: yellow;<br />
}<br />
<br />
=== Combining Selectors ===<br />
<br />
Often, you will need to combine several selectors to target the right elements. CSS selectors can be chained together in many ways. I won't outline<br />
them all here, but here are a few ways they can be chained.<br />
<br />
'''More Specific Selectors'''<br />
<br />
Sometimes, you might want to only target HTML tags that are of a certain class. You can target tags that have a certain class by listing the tag,<br />
immediately folowed by the class name, with no spaces. For example, only target list items with the "selected" class.<br />
<br />
li.selected {<br />
background: yellow;<br />
}<br />
<br />
'''Child Elements'''<br />
<br />
You can also target elements that are children of other elements. If you list a CSS selector followed by a space and then another CSS selector, the<br />
second selector must be a child element of the first selector. For example, only target li items that are inside of the element with an ID of "nav":<br />
<br />
#nav li {<br />
border: 1px solid green;<br />
}<br />
<br />
'''Multiple Classes'''<br />
<br />
If you'd like to target elements that have multiple classes on them, you can chain classes together by listing them one after another, with no spaces.<br />
The following CSS selector will target elements that have both the "disabled" and the "broken" class on them:<br />
<br />
.disabled.broken {<br />
color: red;<br />
background: gray;<br />
}<br />
<br />
'''Complex Selectors'''<br />
<br />
CSS selectors can be as simple or as complex as you want. This selector will target list items with a class "todo" that are inside of a paragraph tag,<br />
inside of the element with an id of "content":<br />
<br />
#content p li.todo {<br />
color: yellow;<br />
}<br />
<br />
There are many other ways to target elements with CSS. This has just been a very basic introduction. If you'd like to read more about CSS, W3Schools<br />
has a good introductory tutorial [http://www.w3schools.com/css/ here].<br />
<br />
<br />
== jQuery ==<br />
<br />
jQuery offers more functionality than I can cover in one class. This week I'll start out with some basic functionality that will get<br />
you started with using the library.<br />
<br />
=== Including jQuery (or Other Libraries) ===<br />
<br />
Before you can start using jQuery, or any other library that you want to use with your page, you will need to include<br />
the library code. There are two options for including the jQuery code. The first option is to download the code for the library and include<br />
it with the rest of your project. The second option is to include a reference to a hosted version of jQuery.<br />
<br />
==== Option 1: Download jQuery Locally ====<br />
<br />
The jQuery library can be downloaded from the [http://jQuery.com jQuery homepage]. Once you've downloaded the code and saved it<br />
to a file called ''jQuery.js'' (or whatever named makes the most sense to you), you can include the code on your page, just like you've<br />
been including the code so far.<br />
<br />
Say you downloaded the file, named it ''jQuery.js'' and stored it in your ''javascripts'' folder. To include<br />
it on your page, you'd simple add the following line to your code:<br />
<br />
&lt;script src=&quot;javascript/jQuery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br />
<br />
Make sure the script is included on your page before any of the scripts that take advantage of jQuery. Otherwise, your scripts won't be<br />
able to find jQuery and won't work.<br />
<br />
The downside to using this option is that you will need to have your own copy of the jQuery code, even though your jQuery code will be exactly<br />
the same as it is on other sites.<br />
<br />
The upside is that it gives you control over the jQuery code you include and allows you work on your project<br />
even without an Internet connection.<br />
<br />
==== Option 2: Use a Hosted jQuery ====<br />
<br />
You can also choose to include a ''hosted'' version of the jQuery code. This means that a 3rd party company is hosting the jQuery code for you.<br />
Usually the code will be hosted by a well known, and reliable company like Google.<br />
<br />
The downside to using this option is that it may take your page slightly longer to load while the JavaScript is loading from the 3rd party<br />
website. This won't always be an issue, because the code will be cached in the browser after the first time the user loads your site, but it's<br />
still an issue to be aware of.<br />
<br />
You also have less control over the jQuery code that you're including and you may be in trouble if the 3rd party site is not responding.<br />
<br />
The upside is that you won't have to manage the jQuery code as part of your project. Also, if other people are using the same 3rd party hosted<br />
jQuery library, the browser will only have to load jQuery the first time it sees a reference to the hosted version.<br />
<br />
=== Selectors with jQuery ===<br />
<br />
One of the best features of jQuery is the ability to find elements on the page using CSS style syntax. So far, we've been finding<br />
elements like this:<br />
<br />
var element = document.getElementById("my-element");<br />
<br />
This works fine, but it requires that we add ids to all of the elements that need are needed by the JavaScript. If we were using CSS<br />
we'd be able to use this syntax to find the element and add styles to it:<br />
<br />
#my-element { border: 1px solid black; }<br />
<br />
With CSS we could also find elements by class:<br />
<br />
.with-border { border: 1px solid black }<br />
<br />
Or we could even target child elements of other elements:<br />
<br />
ul#border-list li { border: 1px solid black; }<br />
<br />
Which lets us find the child elements of certain elements on the page and apply special styles.<br />
<br />
With JavaScript, these kinds of selectors take a lot of code to create. I haven't showed you how to do anything like that that yet, and,<br />
in reality, the complexities of creating code that worked that way across all browsers would be more than one introductory course could cover.<br />
Thankfully, jQuery adds these kinds of selectors to JavaScript already.<br />
<br />
Back to finding our element with the id of ''my-element''. With jQuery, we could simply say this:<br />
<br />
var element = $('#my-element');<br />
<br />
The '''$''' function is a special function added by jQuery that takes in a CSS style selector and returns all of the elements that were<br />
that matched by that selector. <br />
<br />
So, if I wanted to find all of the elements that had the class ''with-border'' I could make a jQuery call like this:<br />
<br />
var elements = $('.with-border');<br />
<br />
Or maybe I wanted to find all of the elements of the unordered list with the id ''border-list'':<br />
<br />
var listItems = $('ul#border-list li');<br />
<br />
Notice how similar the selectors are to CSS? The idea is that any valid CSS selector should work with jQuery. So, you no longer have to<br />
worry about putting an id on every element of the page or about writing your own functions to figure out which elements should be <br />
modified with JavaScript.<br />
<br />
''See more on jQuery selectors [http://docs.jquery.com/Selectors here].''<br />
<br />
'''Note:''' If you look around the web for examples of jQuery being used, you may see some code that uses a function called '''jQuery''', instead of<br />
the '''$''' function. '''With the jQuery library, the jQuery function is exactly the same as the $ function'''<br />
<br />
=== Events with jQuery ===<br />
<br />
Once you've found an element or a list of elements with jQuery, you can start adding events to it. Events in jQuery work similarly to<br />
events in plain old JavaScript. One of the biggest differences, though, is that I can add multiple event handlers to one element. Let's say<br />
that I wanted to add a click handler to ''my-element''. I could find it and attach an event with jQuery like this:<br />
<br />
function clickHandler() {<br />
alert('hi');<br />
}<br />
<br />
var element = $('#my-element');<br />
element.click(clickHandler);<br />
<br />
Notice that, instead of setting '''onclick''' equal to '''clickHandler''', we are passing '''clickHandler''' into a function called '''click'''.<br />
The reason that jQuery does it this way is because it allows you to add other handers if you wanted:<br />
<br />
function clickHandler() {<br />
alert('hi');<br />
}<br />
<br />
function anotherHandler() {<br />
alert('another');<br />
}<br />
<br />
var element = $('#my-element');<br />
element.click(clickHandler);<br />
element.click(anotherHandler);<br />
<br />
In the example above there are two handler functions, and I've added them both to element using the '''click''' function that jQuery provides.<br />
<br />
Another difference between regular JavaScript and jQuery is that the jQuery function doesn't just return one element, it returns all elements<br />
that match the selector you passed in. Let's say that you had an unordered list on your page like this:<br />
<br />
&lt;ul id=&quot;myList&quot;&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
The list has 3 items and you'd like each item to call a handler when the user mouses over the item. jQuery allows you to select all of the items<br />
and attach and event to all of them at once:<br />
<br />
var listItems = $('#myList li');<br />
listItems.mouseOver(handlerFunction);<br />
<br />
The selector '''#myList li''' finds all of the list items inside of the element with an id of '''myList'''. jQuery returns a collection of all<br />
of the list items. You can then add the event handlers the same way you'd add them to an individual item. In this case, the '''mouseOver'''<br />
function takes in a handler function that will be called whenever the user puts their mouse over any of the list items.<br />
<br />
One other thing to note: just like when you attach an event handler to an event with regular JavaScript, event handlers attached with jQuery<br />
refer back to the element that the handler is tied to by using the '''this''' keyword (as you'll see below).<br />
<br />
''See more on jQuery events [http://docs.jquery.com/Events here] ''<br />
<br />
=== Changing Styles with jQuery ===<br />
<br />
jQuery also has some tricks for changing the styling of elements. Above, we attached an event handler to all of the elements in this list:<br />
<br />
&lt;ul id=&quot;myList&quot;&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
Instead of attaching a generic eventHandler function, let's create a function called '''changeStyle''' that will change the style of each<br />
list item when it's clicked on. Attaching the event handler is simple:<br />
<br />
var listItems = jQuery('#myList li');<br />
listItems.click(changeStyle);<br />
<br />
Now, we need to create a function called '''changeStyle'''. First, let's use the jQuery '''css''' function to directly modify the CSS styles of<br />
each list item:<br />
<br />
function changeStyle()<br />
{<br />
var element = '''jQuery(this)''';<br />
element.'''css({ background: "blue", border: "5px solid black"});'''<br />
}<br />
<br />
There are a couple things going on with this function. First, we're passing '''this''' to the jQuery function. In this case, think of jQuery as<br />
a special wrapper that adds special features to an element. One of these special features the jQuery function adds is the '''css''' function. The '''css'''<br />
function takes in a JavaScript object that represents the CSS styles you'd like to add to the element. Notice that the syntax almost looks<br />
like regular CSS, except we're using it in JavaScript instead of a CSS file.<br />
<br />
Adding CSS directly works fine, but we should be separating our presentation from our behavior. We can do this by defining the styles we'd like<br />
to add as classes in our JavaScript. We can then add the classes using jQuery.<br />
<br />
''In my CSS file:''<br />
<br />
.list-style { background: blue; border: 5px solid black; }<br />
<br />
''In my JavaScript file:''<br />
<br />
function changeStyle()<br />
{<br />
var element = jQuery(this);<br />
element.addClass('list-style');<br />
}<br />
<br />
jQuery takes care of adding multiple classes, so you can add as many classes as you want:<br />
<br />
element.addClass('list-style');<br />
element.addClass('another-class');<br />
<br />
Later, you can go back and remove classes as well:<br />
<br />
element.removeClass('list-style');<br />
<br />
This is the preferred way of modifying the styles in your HTML, so try to avoid directly modifying the CSS styles of an object when you can.<br />
<br />
''See more on CSS manipulation with jQuery [http://docs.jquery.com/CSS here]''.<br />
<br />
=== jQuery Effects ===<br />
<br />
jQuery offers a few built in functions for adding special effects to your page. These are pretty simple effects, but they can come in handy. There<br />
are additional effects that people have written that can be plugged in to jQuery, but, for now, we'll start with the simple built in ones.<br />
<br />
'''Fading'''<br />
<br />
Elements on your page can easily be faded in or faded out with jQuery:<br />
<br />
// Without a specified time<br />
element.'''fadeIn'''();<br />
element.'''fadeOut'''();<br />
<br />
// With a specified time<br />
element.'''fadeIn'''(1000);<br />
element.'''fadeOut'''(3000);<br />
<br />
The the examples at the top fade the element in and out without specifying the amount of time it should take. The examples on the bottom are setting<br />
specific amount of time the effect should take. The effects functions take in the number of milleseconds an effect should take ''(there are<br />
1000 milleseconds in one second)''.<br />
<br />
''See more on effects with jQuery [http://docs.jquery.com/Effects here]''<br />
<br />
== Activity ==<br />
<br />
Download the example jQuery files [http://mattephraim.com/intro_to_javascript_fall_2010/class_5/jquery_examples.zip here]. <br />
I will go over how each of the examples works and give you a chance to modify the scripts.<br />
<br />
== Assignment 3 ==<br />
<br />
'''Due Friday October 15th at 11pm'''<br />
<br />
Download the template files [http://mattephraim.com/intro_to_javascript_fall_2010/class_5/assignment_3.zip here] <br />
and make the index.html page behave the way it is described.<br />
Be sure to use proper indentation and variable/function names and add comments to any functions or variables that might be unclear to others.<br />
<br />
Zip all of the files for your project and email them to me before the due date.<br />
<br />
Feel free to email me at mephraim@colum.edu if you have any questions.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_5&diff=17757Introduction to JavaScript Fall 2010 Class 52010-10-05T22:10:01Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
So far, we've been writing all of our JavaScript by hand. You may have noticed that some if it gets repetitive.<br />
Typing '''document.getElementById''' and giving all of the elements on your page ids might start to seem like<br />
a chore. Thankfully, there are ways to streamline the process of adding JavaScript to your page.<br />
<br />
One thing that you can do to speed up your JavaScript development is use a JavaScript library. '''JavaScript libraries'''<br />
are collections of handy functions and tools that have been written by other people. When you include<br />
a JavaScript library on your page you can take advantage of the functionality that other people have written.<br />
<br />
In this class, we will be mainly focusing on a library called [http://jquery.com jQuery]. jQuery is an open source<br />
library that provides utlities for adding JavaScript event handlers to page elements and for manipulating HTML elements<br />
using JavaScript.<br />
<br />
== A Word About CSS ==<br />
<br />
One important element that you will need to understand before using jQuery is Cascading Style Sheets (CSS). If you don't already know<br />
how to use CSS, here is a brief summary of the basic elements of CSS.<br />
<br />
As I have mentioned before in this class, CSS is used for styling the HTML elements of your page. CSS consists of selectors, which are used<br />
to target HTML elements on the page, and styles, which are used to style the elements that are being targeted.<br />
<br />
For example, the following piece of code targets elements that have the class name .callout, and gives them a blue border that is 3 pixels thick:<br />
<br />
.callout {<br />
border: 3px solid blue;<br />
}<br />
<br />
=== Selectors ===<br />
<br />
'''Tag'''<br />
<br />
Tag selectors select a type of HTML tag. Each selector matches up with the name of the HTML tag you'd like to target. The following CSS targets all<br />
h3 tags and makes the text inside of them red:<br />
<br />
h3 {<br />
color: red;<br />
}<br />
<br />
'''ID'''<br />
<br />
ID selectors are used to target elements that have a particular ID. ID selectors consist of a pound sign ''(#)'' and the ID you'd like to target.<br />
ID's should be only used one time per page, so an ID selector will target a single item on the page. For example, you could target the element with<br />
an ID of "logo" like this:<br />
<br />
#logo {<br />
float: left;<br />
border: 1px solid blue;<br />
}<br />
<br />
'''Class'''<br />
<br />
Class selectors select all HTML tags of a particular class name. Class selectors consist of a dot ''(.)'' followed by the class name you'd like<br />
to target. So, for example, a CSS rule that targets all elements with a class name of "selected" looks like this:<br />
<br />
.selected {<br />
background: yellow;<br />
}<br />
<br />
=== Combining Selectors ===<br />
<br />
Often, you will need to combine several selectors to target the right elements. CSS selectors can be chained together in many ways. I won't outline<br />
them all here, but here are a few ways they can be chained.<br />
<br />
'''More Specific Selectors'''<br />
<br />
Sometimes, you might want to only target HTML tags that are of a certain class. You can target tags that have a certain class by listing the tag,<br />
immediately folowed by the class name, with no spaces. For example, only target list items with the "selected" class.<br />
<br />
li.selected {<br />
background: yellow;<br />
}<br />
<br />
'''Child Elements'''<br />
<br />
You can also target elements that are children of other elements. If you list a CSS selector followed by a space and then another CSS selector, the<br />
second selector must be a child element of the first selector. For example, only target li items that are inside of the element with an ID of "nav":<br />
<br />
#nav li {<br />
border: 1px solid green;<br />
}<br />
<br />
'''Multiple Classes'''<br />
<br />
If you'd like to target elements that have multiple classes on them, you can chain classes together by listing them one after another, with no spaces.<br />
The following CSS selector will target elements that have both the "disabled" and the "broken" class on them:<br />
<br />
.disabled.broken {<br />
color: red;<br />
background: gray;<br />
}<br />
<br />
'''Complex Selectors'''<br />
<br />
CSS selectors can be as simple or as complex as you want. This selector will target list items with a class "todo" that are inside of a paragraph tag,<br />
inside of the element with an id of "content":<br />
<br />
#content p li.todo {<br />
color: yellow;<br />
}<br />
<br />
There are many other ways to target elements with CSS. This has just been a very basic introduction. If you'd like to read more about CSS, W3Schools<br />
has a good introductory tutorial [http://www.w3schools.com/css/ here].<br />
<br />
<br />
== jQuery ==<br />
<br />
jQuery offers more functionality than I can cover in one class. This week I'll start out with some basic functionality that will get<br />
you started with using the library.<br />
<br />
=== Including jQuery (or Other Libraries) ===<br />
<br />
Before you can start using jQuery, or any other library that you want to use with your page, you will need to include<br />
the library code. There are two options for including the jQuery code. The first option is to download the code for the library and include<br />
it with the rest of your project. The second option is to include a reference to a hosted version of jQuery.<br />
<br />
==== Option 1: Download jQuery Locally ====<br />
<br />
The jQuery library can be downloaded from the [http://jQuery.com jQuery homepage]. Once you've downloaded the code and saved it<br />
to a file called ''jQuery.js'' (or whatever named makes the most sense to you), you can include the code on your page, just like you've<br />
been including the code so far.<br />
<br />
Say you downloaded the file, named it ''jQuery.js'' and stored it in your ''javascripts'' folder. To include<br />
it on your page, you'd simple add the following line to your code:<br />
<br />
&lt;script src=&quot;javascript/jQuery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br />
<br />
Make sure the script is included on your page before any of the scripts that take advantage of jQuery. Otherwise, your scripts won't be<br />
able to find jQuery and won't work.<br />
<br />
The downside to using this option is that you will need to have your own copy of the jQuery code, even though your jQuery code will be exactly<br />
the same as it is on other sites.<br />
<br />
The upside is that it gives you control over the jQuery code you include and allows you work on your project<br />
even without an Internet connection.<br />
<br />
==== Option 2: Use a Hosted jQuery ====<br />
<br />
You can also choose to include a ''hosted'' version of the jQuery code. This means that a 3rd party company is hosting the jQuery code for you.<br />
Usually the code will be hosted by a well known, and reliable company like Google.<br />
<br />
The downside to using this option is that it may take your page slightly longer to load while the JavaScript is loading from the 3rd party<br />
website. This won't always be an issue, because the code will be cached in the browser after the first time the user loads your site, but it's<br />
still an issue to be aware of.<br />
<br />
You also have less control over the jQuery code that you're including and you may be in trouble if the 3rd party site is not responding.<br />
<br />
The upside is that you won't have to manage the jQuery code as part of your project. Also, if other people are using the same 3rd party hosted<br />
jQuery library, the browser will only have to load jQuery the first time it sees a reference to the hosted version.<br />
<br />
=== Selectors with jQuery ===<br />
<br />
One of the best features of jQuery is the ability to find elements on the page using CSS style syntax. So far, we've been finding<br />
elements like this:<br />
<br />
var element = document.getElementById("my-element");<br />
<br />
This works fine, but it requires that we add ids to all of the elements that need are needed by the JavaScript. If we were using CSS<br />
we'd be able to use this syntax to find the element and add styles to it:<br />
<br />
#my-element { border: 1px solid black; }<br />
<br />
With CSS we could also find elements by class:<br />
<br />
.with-border { border: 1px solid black }<br />
<br />
Or we could even target child elements of other elements:<br />
<br />
ul#border-list li { border: 1px solid black; }<br />
<br />
Which lets us find the child elements of certain elements on the page and apply special styles.<br />
<br />
With JavaScript, these kinds of selectors take a lot of code to create. I haven't showed you how to do anything like that that yet, and,<br />
in reality, the complexities of creating code that worked that way across all browsers would be more than one introductory course could cover.<br />
Thankfully, jQuery adds these kinds of selectors to JavaScript already.<br />
<br />
Back to finding our element with the id of ''my-element''. With jQuery, we could simply say this:<br />
<br />
var element = $('#my-element');<br />
<br />
The '''$''' function is a special function added by jQuery that takes in a CSS style selector and returns all of the elements that were<br />
that matched by that selector. <br />
<br />
So, if I wanted to find all of the elements that had the class ''with-border'' I could make a jQuery call like this:<br />
<br />
var elements = $('.with-border');<br />
<br />
Or maybe I wanted to find all of the elements of the unordered list with the id ''border-list'':<br />
<br />
var listItems = $('ul#border-list li');<br />
<br />
Notice how similar the selectors are to CSS? The idea is that any valid CSS selector should work with jQuery. So, you no longer have to<br />
worry about putting an id on every element of the page or about writing your own functions to figure out which elements should be <br />
modified with JavaScript.<br />
<br />
''See more on jQuery selectors [http://docs.jquery.com/Selectors here].''<br />
<br />
'''Note:''' If you look around the web for examples of jQuery being used, you may see some code that uses a function called '''jQuery''', instead of<br />
the '''$''' function. '''With the jQuery library, the jQuery function is exactly the same as the $ function'''<br />
<br />
=== Events with jQuery ===<br />
<br />
Once you've found an element or a list of elements with jQuery, you can start adding events to it. Events in jQuery work similarly to<br />
events in plain old JavaScript. One of the biggest differences, though, is that I can add multiple event handlers to one element. Let's say<br />
that I wanted to add a click handler to ''my-element''. I could find it and attach an event with jQuery like this:<br />
<br />
function clickHandler() {<br />
alert('hi');<br />
}<br />
<br />
var element = $('#my-element');<br />
element.click(clickHandler);<br />
<br />
Notice that, instead of setting '''onclick''' equal to '''clickHandler''', we are passing '''clickHandler''' into a function called '''click'''.<br />
The reason that jQuery does it this way is because it allows you to add other handers if you wanted:<br />
<br />
function clickHandler() {<br />
alert('hi');<br />
}<br />
<br />
function anotherHandler() {<br />
alert('another');<br />
}<br />
<br />
var element = $('#my-element');<br />
element.click(clickHandler);<br />
element.click(anotherHandler);<br />
<br />
In the example above there are two handler functions, and I've added them both to element using the '''click''' function that jQuery provides.<br />
<br />
Another difference between regular JavaScript and jQuery is that the jQuery function doesn't just return one element, it returns all elements<br />
that match the selector you passed in. Let's say that you had an unordered list on your page like this:<br />
<br />
&lt;ul id=&quot;myList&quot;&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
The list has 3 items and you'd like each item to call a handler when the user mouses over the item. jQuery allows you to select all of the items<br />
and attach and event to all of them at once:<br />
<br />
var listItems = $('#myList li');<br />
listItems.mouseOver(handlerFunction);<br />
<br />
The selector '''#myList li''' finds all of the list items inside of the element with an id of '''myList'''. jQuery returns a collection of all<br />
of the list items. You can then add the event handlers the same way you'd add them to an individual item. In this case, the '''mouseOver'''<br />
function takes in a handler function that will be called whenever the user puts their mouse over any of the list items.<br />
<br />
One other thing to note: just like when you attach an event handler to an event with regular JavaScript, event handlers attached with jQuery<br />
refer back to the element that the handler is tied to by using the '''this''' keyword (as you'll see below).<br />
<br />
''See more on jQuery events [http://docs.jquery.com/Events here] ''<br />
<br />
=== Changing Styles with jQuery ===<br />
<br />
jQuery also has some tricks for changing the styling of elements. Above, we attached an event handler to all of the elements in this list:<br />
<br />
&lt;ul id=&quot;myList&quot;&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
Instead of attaching a generic eventHandler function, let's create a function called '''changeStyle''' that will change the style of each<br />
list item when it's clicked on. Attaching the event handler is simple:<br />
<br />
var listItems = jQuery('#myList li');<br />
listItems.click(changeStyle);<br />
<br />
Now, we need to create a function called '''changeStyle'''. First, let's use the jQuery '''css''' function to directly modify the CSS styles of<br />
each list item:<br />
<br />
function changeStyle()<br />
{<br />
var element = '''jQuery(this)''';<br />
element.'''css({ background: "blue", border: "5px solid black"});'''<br />
}<br />
<br />
There are a couple things going on with this function. First, we're passing '''this''' to the jQuery function. In this case, think of jQuery as<br />
a special wrapper that adds special features to an element. One of these special features the jQuery function adds is the '''css''' function. The '''css'''<br />
function takes in a JavaScript object that represents the CSS styles you'd like to add to the element. Notice that the syntax almost looks<br />
like regular CSS, except we're using it in JavaScript instead of a CSS file.<br />
<br />
Adding CSS directly works fine, but we should be separating our presentation from our behavior. We can do this by defining the styles we'd like<br />
to add as classes in our JavaScript. We can then add the classes using jQuery.<br />
<br />
''In my CSS file:''<br />
<br />
.list-style { background: blue; border: 5px solid black; }<br />
<br />
''In my JavaScript file:''<br />
<br />
function changeStyle()<br />
{<br />
var element = jQuery(this);<br />
element.addClass('list-style');<br />
}<br />
<br />
jQuery takes care of adding multiple classes, so you can add as many classes as you want:<br />
<br />
element.addClass('list-style');<br />
element.addClass('another-class');<br />
<br />
Later, you can go back and remove classes as well:<br />
<br />
element.removeClass('list-style');<br />
<br />
This is the preferred way of modifying the styles in your HTML, so try to avoid directly modifying the CSS styles of an object when you can.<br />
<br />
''See more on CSS manipulation with jQuery [http://docs.jquery.com/CSS here]''.<br />
<br />
=== jQuery Effects ===<br />
<br />
jQuery offers a few built in functions for adding special effects to your page. These are pretty simple effects, but they can come in handy. There<br />
are additional effects that people have written that can be plugged in to jQuery, but, for now, we'll start with the simple built in ones.<br />
<br />
'''Fading'''<br />
<br />
Elements on your page can easily be faded in or faded out with jQuery:<br />
<br />
// Without a specified time<br />
element.'''fadeIn'''();<br />
element.'''fadeOut'''();<br />
<br />
// With a specified time<br />
element.'''fadeIn'''(1000);<br />
element.'''fadeOut'''(3000);<br />
<br />
The the examples at the top fade the element in and out without specifying the amount of time it should take. The examples on the bottom are setting<br />
specific amount of time the effect should take. The effects functions take in the number of milleseconds an effect should take ''(there are<br />
1000 milleseconds in one second)''.<br />
<br />
''See more on effects with jQuery [http://docs.jquery.com/Effects here]''<br />
<br />
== Activity ==<br />
<br />
Download the example jQuery files [http://mattephraim.com/intro_to_javascript_fall_2010/class_5/jquery_examples.zip here]. <br />
I will go over how each of the examples works and give you a chance to modify the scripts.<br />
<br />
== Assignment 3 ==<br />
<br />
'''Due Friday October 15th at 11pm'''<br />
<br />
Download the template files [http://mattephraim.com/intro_to_javascript_fall_2010/class_5/assignment_3.zip here] <br />
and make the index.html page behave the way it is described.<br />
Be sure to use proper indentation and variable/function names and add comments to any functions or variables that might be unclear to others.<br />
<br />
Zip all of the files for your project and email them to me before the due date.<br />
<br />
Feel free to email me at mephraim@colum.edu if you have any questions.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17756Introduction to JavaScript Fall 20102010-10-05T21:58:44Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
* Class 5 (10/5/2010): [[Introduction_to_JavaScript_Fall_2010_Class_5|Introduction to jQuery]]<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_4&diff=17755Introduction to JavaScript Fall 2010 Class 42010-10-05T21:57:43Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles.<br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about yet is coding style. Like the English language, JavaScript has it's own<br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this<br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names'''<br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch<br />
to a new ''block'' of code, you should indent 2 spaces.<br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Coding Style Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== JavaScript Event Links ==<br />
<br />
In addition to the wiki, you may find these links helpful<br />
<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://erkie.github.com/ Turn any page into asteroids]<br />
<br />
This piece of JavaScript uses some JavaScript trickery to turn any webpage into a game of asteroids. Using a JavaScript snippet<br />
called a '''[http://en.wikipedia.org/wiki/Bookmarklet bookmarket]''' to allow you to bookmark a piece of JavaScript and reuse it on<br />
any site.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
<br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
<br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
<br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
<br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
<br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
<br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
<br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
<br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_5&diff=17754Introduction to JavaScript Fall 2010 Class 52010-10-05T21:53:11Z<p>Matthew.ephraim: Created page with 'Back to Introduction to JavaScript Fall 2010 == Introduction == So far, we've been writing all of our JavaScript by hand. You may have …'</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
So far, we've been writing all of our JavaScript by hand. You may have noticed that some if it gets repetitive.<br />
Typing '''document.getElementById''' and giving all of the elements on your page ids might start to seem like<br />
a chore. Thankfully, there are ways to streamline the process of adding JavaScript to your page.<br />
<br />
One thing that you can do to speed up your JavaScript development is use a JavaScript library. '''JavaScript libraries'''<br />
are collections of handy functions and tools that have been written by other people. When you include<br />
a JavaScript library on your page you can take advantage of the functionality that other people have written.<br />
<br />
In this class, we will be mainly focusing on a library called [http://jquery.com jQuery]. jQuery is an open source<br />
library that provides utlities for adding JavaScript event handlers to page elements and for manipulating HTML elements<br />
using JavaScript.<br />
<br />
== A Word About CSS ==<br />
<br />
One important thing that you will need to know about before using jQuery is Cascading Style Sheets (CSS). If you don't already know<br />
how to use CSS, here is a brief summary of the basic elements of CSS.<br />
<br />
As I have mentioned before in this class, CSS is used for styling the HTML elements of your page. CSS consists of selectors, which are used<br />
to target HTML elements on the page, and styles, which are used to style the elements that are being targeted.<br />
<br />
For example, the following piece of code targets elements that have the class name .callout, and gives them a blue border that is 3 pixels thick:<br />
<br />
.callout {<br />
border: 3px solid blue;<br />
}<br />
<br />
=== Selectors ===<br />
<br />
'''Tag'''<br />
<br />
Tag selectors select a type of HTML tag. Each selector matches up with the name of the HTML tag you'd like to target. The following CSS targets all<br />
h3 tags and makes the text inside of them red:<br />
<br />
h3 {<br />
color: red;<br />
}<br />
<br />
'''ID'''<br />
<br />
ID selectors are used to target elements that have a particular ID. ID selectors consist of a pound sign ''(#)'' and the ID you'd like to target.<br />
ID's should be only used one time per page, so an ID selector will target a single item on the page. For example, you could target the element with<br />
an ID of "logo" like this:<br />
<br />
#logo {<br />
float: left;<br />
border: 1px solid blue;<br />
}<br />
<br />
'''Class'''<br />
<br />
Class selectors select all HTML tags of a particular class name. Class selectors consist of a dot ''(.)'' followed by the class name you'd like<br />
to target. So, for example, a CSS rule that targets all elements with a class name of "selected" looks like this:<br />
<br />
.selected {<br />
background: yellow;<br />
}<br />
<br />
=== Combining Selectors ===<br />
<br />
Often, you will need to combine several selectors to target the right elements. CSS selectors can be chained together in many ways. I won't outline<br />
them all here, but here are a few ways they can be chained.<br />
<br />
'''More Specific Selectors'''<br />
<br />
Sometimes, you might want to only target HTML tags that are of a certain class. You can target tags that have a certain class by listing the tag,<br />
immediately folowed by the class name, with no spaces. For example, only target list items with the "selected" class.<br />
<br />
li.selected {<br />
background: yellow;<br />
}<br />
<br />
'''Child Elements'''<br />
<br />
You can also target elements that are children of other elements. If you list a CSS selector followed by a space and then another CSS selector, the<br />
second selector must be a child element of the first selector. For example, only target li items that are inside of the element with an ID of "nav":<br />
<br />
#nav li {<br />
border: 1px solid green;<br />
}<br />
<br />
'''Multiple Classes'''<br />
<br />
If you'd like to target elements that have multiple classes on them, you can chain classes together by listing them one after another, with no spaces.<br />
The following CSS selector will target elements that have both the "disabled" and the "broken" class on them:<br />
<br />
.disabled.broken {<br />
color: red;<br />
background: gray;<br />
}<br />
<br />
'''Complex Selectors'''<br />
<br />
CSS selectors can be as simple or as complex as you want. This selector will target list items with a class "todo" that are inside of a paragraph tag,<br />
inside of the element with an id of "content":<br />
<br />
#content p li.todo {<br />
color: yellow;<br />
}<br />
<br />
There are many other ways to target elements with CSS. This has just been a very basic introduction. If you'd like to read more about CSS, W3Schools<br />
has a good introductory tutorial [http://www.w3schools.com/css/ here].<br />
<br />
<br />
== jQuery ==<br />
<br />
jQuery offers more functionality than I can cover in one class. This week I'll start out with some basic functionality that will get<br />
you started with using the library.<br />
<br />
=== Including jQuery (or Other Libraries) ===<br />
<br />
Before you can start using jQuery, or any other library that you want to use with your page, you will need to include<br />
the library code. There are two options for including the jQuery code. The first option is to download the code for the library and include<br />
it with the rest of your project. The second option is to include a reference to a hosted version of jQuery.<br />
<br />
==== Option 1: Download jQuery Locally ====<br />
<br />
The jQuery library can be downloaded from the [http://jQuery.com jQuery homepage]. Once you've downloaded the code and saved it<br />
to a file called ''jQuery.js'' (or whatever named makes the most sense to you), you can include the code on your page, just like you've<br />
been including the code so far.<br />
<br />
Say you downloaded the file, named it ''jQuery.js'' and stored it in your ''javascripts'' folder. To include<br />
it on your page, you'd simple add the following line to your code:<br />
<br />
&lt;script src=&quot;javascript/jQuery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;<br />
<br />
Make sure the script is included on your page before any of the scripts that take advantage of jQuery. Otherwise, your scripts won't be<br />
able to find jQuery and won't work.<br />
<br />
The downside to using this option is that you will need to have your own copy of the jQuery code, even though your jQuery code will be exactly<br />
the same as it is on other sites.<br />
<br />
The upside is that it gives you control over the jQuery code you include and allows you work on your project<br />
even without an Internet connection.<br />
<br />
==== Option 2: Use a Hosted jQuery ====<br />
<br />
You can also choose to include a ''hosted'' version of the jQuery code. This means that a 3rd party company is hosting the jQuery code for you.<br />
Usually the code will be hosted by a well known, and reliable company like Google.<br />
<br />
The downside to using this option is that it may take your page slightly longer to load while the JavaScript is loading from the 3rd party<br />
website. This won't always be an issue, because the code will be cached in the browser after the first time the user loads your site, but it's<br />
still an issue to be aware of.<br />
<br />
You also have less control over the jQuery code that you're including and you may be in trouble if the 3rd party site is not responding.<br />
<br />
The upside is that you won't have to manage the jQuery code as part of your project. Also, if other people are using the same 3rd party hosted<br />
jQuery library, the browser will only have to load jQuery the first time it sees a reference to the hosted version.<br />
<br />
=== Selectors with jQuery ===<br />
<br />
One of the best features of jQuery is the ability to find elements on the page using CSS style syntax. So far, we've been finding<br />
elements like this:<br />
<br />
var element = document.getElementById("my-element");<br />
<br />
This works fine, but it requires that we add ids to all of the elements that need are needed by the JavaScript. If we were using CSS<br />
we'd be able to use this syntax to find the element and add styles to it:<br />
<br />
#my-element { border: 1px solid black; }<br />
<br />
With CSS we could also find elements by class:<br />
<br />
.with-border { border: 1px solid black }<br />
<br />
Or we could even target child elements of other elements:<br />
<br />
ul#border-list li { border: 1px solid black; }<br />
<br />
Which lets us find the child elements of certain elements on the page and apply special styles.<br />
<br />
With JavaScript, these kinds of selectors take a lot of code to create. I haven't showed you how to do anything like that that yet, and,<br />
in reality, the complexities of creating code that worked that way across all browsers would be more than one introductory course could cover.<br />
Thankfully, jQuery adds these kinds of selectors to JavaScript already.<br />
<br />
Back to finding our element with the id of ''my-element''. With jQuery, we could simply say this:<br />
<br />
var element = $('#my-element');<br />
<br />
The '''$''' function is a special function added by jQuery that takes in a CSS style selector and returns all of the elements that were<br />
that matched by that selector. <br />
<br />
So, if I wanted to find all of the elements that had the class ''with-border'' I could make a jQuery call like this:<br />
<br />
var elements = $('.with-border');<br />
<br />
Or maybe I wanted to find all of the elements of the unordered list with the id ''border-list'':<br />
<br />
var listItems = $('ul#border-list li');<br />
<br />
Notice how similar the selectors are to CSS? The idea is that any valid CSS selector should work with jQuery. So, you no longer have to<br />
worry about putting an id on every element of the page or about writing your own functions to figure out which elements should be <br />
modified with JavaScript.<br />
<br />
''See more on jQuery selectors [http://docs.jquery.com/Selectors here].''<br />
<br />
'''Note:''' If you look around the web for examples of jQuery being used, you may see some code that uses a function called '''jQuery''', instead of<br />
the '''$''' function. '''With the jQuery library, the jQuery function is exactly the same as the $ function'''<br />
<br />
=== Events with jQuery ===<br />
<br />
Once you've found an element or a list of elements with jQuery, you can start adding events to it. Events in jQuery work similarly to<br />
events in plain old JavaScript. One of the biggest differences, though, is that I can add multiple event handlers to one element. Let's say<br />
that I wanted to add a click handler to ''my-element''. I could find it and attach an event with jQuery like this:<br />
<br />
function clickHandler() {<br />
alert('hi');<br />
}<br />
<br />
var element = $('#my-element');<br />
element.click(clickHandler);<br />
<br />
Notice that, instead of setting '''onclick''' equal to '''clickHandler''', we are passing '''clickHandler''' into a function called '''click'''.<br />
The reason that jQuery does it this way is because it allows you to add other handers if you wanted:<br />
<br />
function clickHandler() {<br />
alert('hi');<br />
}<br />
<br />
function anotherHandler() {<br />
alert('another');<br />
}<br />
<br />
var element = $('#my-element');<br />
element.click(clickHandler);<br />
element.click(anotherHandler);<br />
<br />
In the example above there are two handler functions, and I've added them both to element using the '''click''' function that jQuery provides.<br />
<br />
Another difference between regular JavaScript and jQuery is that the jQuery function doesn't just return one element, it returns all elements<br />
that match the selector you passed in. Let's say that you had an unordered list on your page like this:<br />
<br />
&lt;ul id=&quot;myList&quot;&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
The list has 3 items and you'd like each item to call a handler when the user mouses over the item. jQuery allows you to select all of the items<br />
and attach and event to all of them at once:<br />
<br />
var listItems = $('#myList li');<br />
listItems.mouseOver(handlerFunction);<br />
<br />
The selector '''#myList li''' finds all of the list items inside of the element with an id of '''myList'''. jQuery returns a collection of all<br />
of the list items. You can then add the event handlers the same way you'd add them to an individual item. In this case, the '''mouseOver'''<br />
function takes in a handler function that will be called whenever the user puts their mouse over any of the list items.<br />
<br />
One other thing to note: just like when you attach an event handler to an event with regular JavaScript, event handlers attached with jQuery<br />
refer back to the element that the handler is tied to by using the '''this''' keyword (as you'll see below).<br />
<br />
''See more on jQuery events [http://docs.jquery.com/Events here] ''<br />
<br />
=== Changing Styles with jQuery ===<br />
<br />
jQuery also has some tricks for changing the styling of elements. Above, we attached an event handler to all of the elements in this list:<br />
<br />
&lt;ul id=&quot;myList&quot;&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;li&gt;Item&lt;/li&gt;<br />
&lt;/ul&gt;<br />
<br />
Instead of attaching a generic eventHandler function, let's create a function called '''changeStyle''' that will change the style of each<br />
list item when it's clicked on. Attaching the event handler is simple:<br />
<br />
var listItems = jQuery('#myList li');<br />
listItems.click(changeStyle);<br />
<br />
Now, we need to create a function called '''changeStyle'''. First, let's use the jQuery '''css''' function to directly modify the CSS styles of<br />
each list item:<br />
<br />
function changeStyle()<br />
{<br />
var element = '''jQuery(this)''';<br />
element.'''css({ background: "blue", border: "5px solid black"});'''<br />
}<br />
<br />
There are a couple things going on with this function. First, we're passing '''this''' to the jQuery function. In this case, think of jQuery as<br />
a special wrapper that adds special features to an element. One of these special features the jQuery function adds is the '''css''' function. The '''css'''<br />
function takes in a JavaScript object that represents the CSS styles you'd like to add to the element. Notice that the syntax almost looks<br />
like regular CSS, except we're using it in JavaScript instead of a CSS file.<br />
<br />
Adding CSS directly works fine, but we should be separating our presentation from our behavior. We can do this by defining the styles we'd like<br />
to add as classes in our JavaScript. We can then add the classes using jQuery.<br />
<br />
''In my CSS file:''<br />
<br />
.list-style { background: blue; border: 5px solid black; }<br />
<br />
''In my JavaScript file:''<br />
<br />
function changeStyle()<br />
{<br />
var element = jQuery(this);<br />
element.addClass('list-style');<br />
}<br />
<br />
jQuery takes care of adding multiple classes, so you can add as many classes as you want:<br />
<br />
element.addClass('list-style');<br />
element.addClass('another-class');<br />
<br />
Later, you can go back and remove classes as well:<br />
<br />
element.removeClass('list-style');<br />
<br />
This is the preferred way of modifying the styles in your HTML, so try to avoid directly modifying the CSS styles of an object when you can.<br />
<br />
''See more on CSS manipulation with jQuery [http://docs.jquery.com/CSS here]''.<br />
<br />
=== jQuery Effects ===<br />
<br />
jQuery offers a few built in functions for adding special effects to your page. These are pretty simple effects, but they can come in handy. There<br />
are additional effects that people have written that can be plugged in to jQuery, but, for now, we'll start with the simple built in ones.<br />
<br />
'''Fading'''<br />
<br />
Elements on your page can easily be faded in or faded out with jQuery:<br />
<br />
// Without a specified time<br />
element.'''fadeIn'''();<br />
element.'''fadeOut'''();<br />
<br />
// With a specified time<br />
element.'''fadeIn'''(1000);<br />
element.'''fadeOut'''(3000);<br />
<br />
The the examples at the top fade the element in and out without specifying the amount of time it should take. The examples on the bottom are setting<br />
specific amount of time the effect should take. The effects functions take in the number of milleseconds an effect should take ''(there are<br />
1000 milleseconds in one second)''.<br />
<br />
''See more on effects with jQuery [http://docs.jquery.com/Effects here]''<br />
<br />
== Activity ==<br />
<br />
Download the example jQuery files [http://mattephraim.com/intro_to_javascript_fall_2010/class_5/jquery_examples.zip here]. <br />
I will go over how each of the examples works and give you a chance to modify the scripts.<br />
<br />
== Assignment 3 ==<br />
<br />
'''Due Friday October 15th at 11pm'''<br />
<br />
Download the template files [http://mattephraim.com/intro_to_javascript_fall_2010/class_5/assignment_3.zip here] <br />
and make the index.html page behave the way it is described.<br />
Be sure to use proper indentation and variable/function names and add comments to any functions or variables that might be unclear to others.<br />
<br />
Zip all of the files for your project and email them to me before the due date.<br />
<br />
Feel free to email me at mephraim@colum.edu if you have any questions.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010&diff=17732Introduction to JavaScript Fall 20102010-09-28T23:27:50Z<p>Matthew.ephraim: /* Class Schedule */</p>
<hr />
<div>== Introduction ==<br />
<br />
JavaScript is a scrappy little language that has seen a lot of changes since its introduction in 1995. Though the language has often been abused, there has been a resurgence of interest since the introduction of highly dynamic web applications like Gmail and Google Maps, which take full of advantage of JavaScript's capabilities.<br />
<br />
This class will treat JavaScript with the respect that it deserves. Instead of relying on poorly designed tools to generate half-baked JavaScript, we will be hand writing clean and compact JavaScript.<br />
<br />
I fully expect that this class will include students with little to no experience with programming or JavaScript. Luckily, JavaScript is a simple language to work with. Unlike many other languages, JavaScript doesn't require any fancy development environments or expensive tools. I hope that everyone will come away from this class knowing a lot more about JavaScript than they did before starting.<br />
<br />
== Who's teaching this class? ==<br />
<br />
My name is [http://www.mattephraim.com Matt Ephraim]. I am a web developer at [http://metromix.com Metromix] and I'm currently working on a Master's degree in Information Architecture at [http://www.iit.edu IIT].<br />
<br />
You can contact me at [mailto:mephraim@colum.edu mephraim@colum.edu].<br />
<br />
I won't have any office hours on campus, but if you would like to meet with me, I am available most days after 5pm and always available after class.<br />
<br />
== Tools for this class ==<br />
<br />
This is a list of tools that will come in handy for JavaScript development. I will update this list as the class goes on.<br />
<br />
=== Text Editors ===<br />
<br />
'''For Windows'''<br />
* [http://notepad-plus.sourceforge.net/uk/site.htm Notepad++] (free)<br />
* [http://www.e-texteditor.com/ e TextEditor]<br />
* [http://www.scintilla.org/SciTEDownload.html SciTE] (free and open source)<br />
<br />
'''For OS X'''<br />
* [http://www.barebones.com/products/TextWrangler/download.html TextWrangler] (free)<br />
* [http://macromates.com/ TextMate]<br />
* [http://www.panic.com/coda/ Coda]<br />
<br />
=== Browser Tools ===<br />
<br />
'''Tools for Firefox'''<br />
* [http://getfirebug.com/ Firebug]<br />
* [https://addons.mozilla.org/en-US/firefox/addon/60 Web Developer Toolbar]<br />
<br />
=== Books ===<br />
<br />
I won't be teaching directly out of a book for this class, but there are a few books that will come in handy:<br />
<br />
[http://www.amazon.com/JavaScript-Definitive-Guide-David-Flanagan/dp/0596101996/ JavaScript: the Definitive Guide]: this is, essentially, the JavaScript Bible. If you want to know where much of the content of this course comes from, look no further than this book. I highly recommend buying it. And make sure to get the latest edition (currently, the 5th is the latest).<br />
<br />
[http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/ JavaScript: the Good Parts]: this is a brief and opinionated book, but if you're already somewhat familiar with JavaScript, it makes a good reference. It's no substitute for the Definitive Guide, but it contains some good information.<br />
<br />
== Resources ==<br />
<br />
This is a list of resources that will come in handy for this class.<br />
<br />
* [http://www.w3schools.com/js/default.asp W3Schools JavaScript reference]<br />
* [https://developer.mozilla.org/en/JavaScript Mozilla JavaScript reference]<br />
* [http://diveintohtml5.org/ Dive Into HTML5 (an online book about HTML5)]<br />
<br />
== Interesting JavaScript Websites ==<br />
<br />
Each week, I will show you an interesting example of JavaScript usage in the wild. You can find a list of all of the websites here.<br />
<br />
* [http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
* [http://www.beautyoftheweb.com/ Microsoft's Beauty of the Web / IE9 Showcase]<br />
<br />
== Class Schedule ==<br />
<br />
* Class 1 (9/7/2010): [[Introduction_to_JavaScript_Fall_2010_Class_1|Introduction]]<br />
* Class 2 (9/14/2010): [[Introduction_to_JavaScript_Fall_2010_Class_2|Javascript Basics Part 1]]<br />
* Class 3 (9/21/2010): [[Introduction_to_JavaScript_Fall_2010_Class_3|Javascript Basics Part 2]]<br />
* Class 4 (9/28/2010): [[Introduction_to_JavaScript_Fall_2010_Class_4|Javascript Events]]<br />
<br />
<br />
<p></p><br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_4&diff=17731Introduction to JavaScript Fall 2010 Class 42010-09-28T22:49:36Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles.<br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about yet is coding style. Like the English language, JavaScript has it's own<br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this<br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names'''<br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch<br />
to a new ''block'' of code, you should indent 2 spaces.<br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Coding Style Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== JavaScript Event Links ==<br />
<br />
In addition to the wiki, you may find these links helpful<br />
<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://erkie.github.com/ Turn any page into asteroids]<br />
<br />
This piece of JavaScript uses some JavaScript trickery to turn any webpage into a game of asteroids. Using a JavaScript snippet<br />
called a '''[http://en.wikipedia.org/wiki/Bookmarklet bookmarket]''' to allow you to bookmark a piece of JavaScript and reuse it on<br />
any site.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<!--<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
--><br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
<!--<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
--><br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<!--<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<!--<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
--><br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
<!--<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<!--<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
--><br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
--><br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
--><br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_4&diff=17730Introduction to JavaScript Fall 2010 Class 42010-09-28T22:48:59Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles.<br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about yet is coding style. Like the English language, JavaScript has it's own<br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this<br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names'''<br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch<br />
to a new ''block'' of code, you should indent 2 spaces.<br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Coding Style Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== JavaScript Event Links ==<br />
<br />
In addition to the wiki, you may find these links helpful<br />
<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://erkie.github.com/ Turn any page into asteroids]<br />
<br />
This piece of JavaScript uses some JavaScript trickery to turn any webpage into a game of asteroids. Using a JavaScript snippet<br />
called a '''[http://en.wikipedia.org/wiki/Bookmarklet bookmarket]''' to allow you to bookmark a piece of JavaScript and reuse it on<br />
any site.<br />
<br />
Click <a href="javascript:var%20s%20=%20document.createElement('script');s.type='text/javascript';document.body.appendChild(s);s.src='http://erkie.github.com/asteroids.min.js';void(0);">here</a> to see the bookmarklet in action.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<!--<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
--><br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
<!--<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
--><br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<!--<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<!--<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
--><br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
<!--<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<!--<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
--><br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
--><br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
--><br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_4&diff=17729Introduction to JavaScript Fall 2010 Class 42010-09-28T22:48:07Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles.<br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about yet is coding style. Like the English language, JavaScript has it's own<br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this<br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names'''<br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch<br />
to a new ''block'' of code, you should indent 2 spaces.<br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Coding Style Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== JavaScript Event Links ==<br />
<br />
In addition to the wiki, you may find these links helpful<br />
<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://erkie.github.com/ Turn any page into asteroids]<br />
<br />
This piece of JavaScript uses some JavaScript trickery to turn any webpage into a game of asteroids. Using a JavaScript snippet<br />
called a '''[http://en.wikipedia.org/wiki/Bookmarklet bookmarket]''' to allow you to bookmark a piece of JavaScript and reuse it on<br />
any site.<br />
<br />
Click [javascript:var%20s%20=%20document.createElement('script');s.type='text/javascript';document.body.appendChild(s);s.src='http://erkie.github.com/asteroids.min.js';void(0); here] to see the bookmarklet in action.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<!--<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
--><br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
<!--<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
--><br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<!--<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<!--<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
--><br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
<!--<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<!--<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
--><br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
--><br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
--><br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_4&diff=17728Introduction to JavaScript Fall 2010 Class 42010-09-28T22:46:19Z<p>Matthew.ephraim: </p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles.<br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about yet is coding style. Like the English language, JavaScript has it's own<br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this<br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names'''<br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch<br />
to a new ''block'' of code, you should indent 2 spaces.<br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Coding Style Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== JavaScript Event Links ==<br />
<br />
In addition to the wiki, you may find these links helpful<br />
<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Today's Interesting JavaScript Site ==<br />
<br />
[http://erkie.github.com/ Turn any page into asteroids]<br />
<br />
This piece of JavaScript uses some JavaScript trickery to turn any webpage into a game of asteroids. Using a JavaScript snippet<br />
called a '''[http://en.wikipedia.org/wiki/Bookmarklet bookmarket]''' to allow you to bookmark a piece of JavaScript and reuse it on<br />
any site.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<!--<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
--><br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
<!--<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
--><br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<!--<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<!--<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
--><br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
<!--<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<!--<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
--><br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
--><br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
--><br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_4&diff=17727Introduction to JavaScript Fall 2010 Class 42010-09-28T22:42:04Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles.<br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about yet is coding style. Like the English language, JavaScript has it's own<br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this<br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names'''<br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch<br />
to a new ''block'' of code, you should indent 2 spaces.<br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Coding Style Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== JavaScript Event Links ==<br />
<br />
In addition to the wiki, you may find these links helpful<br />
<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<!--<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
--><br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
<!--<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
--><br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<!--<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<!--<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
--><br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
<!--<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<!--<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
--><br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
--><br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
--></div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2009_Class_4&diff=17726Introduction to JavaScript Fall 2009 Class 42010-09-28T22:41:48Z<p>Matthew.ephraim: Undo revision 17725 by Matthew.ephraim (Talk)</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2009|Back to Introduction to JavaScript Fall 2009]]<br />
<br />
== Introduction ==<br />
<br />
This week I will talk about using some of the concepts I've shown you the last few weeks to actually<br />
start putting together a web page that uses JavaScript. I want to make sure that everyone understands<br />
the concepts I've presented so far are making sense to everyone, so the majority of the class will<br />
be dedicated to building a simple game that tests your knowledge. ''This game will be your assignment for the week,<br />
but hopefully you will be able to finish it during class time.''<br />
<br />
Before starting the game, there are a few coding style issues that I'd like to cover. <br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about is coding style. Like the English language, JavaScript has it's own <br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this <br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names''' <br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch <br />
to a new ''block'' of code, you should indent 2 spaces. <br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt()<br />
{<br />
if (name === "Matt")<br />
{<br />
alert('hello Matt');<br />
}<br />
else<br />
{<br />
alert('You're not Matt!'); <br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt()<br />
{<br />
if (name === "Matt")<br />
{<br />
alert('hello Matt');<br />
}<br />
else<br />
{<br />
alert('You're not Matt!'); <br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Activity ==<br />
<br />
Today, we will be creating a simple number guessing game. The computer will pick a random number and the user will try to guess<br />
what the number is. If the user guesses too low, the computer will tell them that the number is higher. If the user guesses<br />
too high, the computer will tell them that the number is lower. And if the user guesses the number correctly, the computer<br />
will tell them that they have won.<br />
<br />
=== Step 1 ===<br />
<br />
'''get the template'''<br />
<br />
First, download the [http://mattephraim.com/intro_to_javascript/class_4/game.zip template for the game]. <br />
I have already created a game board for you. The board has a few elements on it and is styled using CSS. <br />
Open up ''game.html'' and look at the html. There is a form with an ''input'' box for the number that the user will guess. <br />
There is also a ''button'' that the user can click to send their guess to the computer. Finally, there is a ''div'' at <br />
the bottom where messages from the computer will be displayed.<br />
<br />
Notice that 3 of the elements have the '''id''' attribute filled out. We are going to use those ids in our JavaScript.<br />
<br />
=== Step 2 ===<br />
<br />
'''test the setupGame function'''<br />
<br />
Open the file called '''behavior.js''' that's in the JavaScript folder. This is the file that contain the program for our <br />
game. Notice that I have already created several functions in the file for you. For now, you can ignore the 2 functions<br />
at the bottom of the page. We will be using these functions later on to make the game work.<br />
<br />
The 2 things that I want you to notice are the empty function called '''setupGame''' and the link that says:<br />
<br />
window.onload = setupGame;<br />
<br />
This line is important. '''window''' is a variable for the browser window and '''onload''' lets you set a function that will run<br />
when the browser window loads. So, what this line of code is saying is "call the function '''setupGame''' when the browser<br />
window loads". In other words, '''setupGame''' is the name of a function that should run as soon as the page loads.<br />
<br />
Right now '''setupGame''' isn't actually doing anything, because it's empty. Modify the function so that it looks like this<br />
<br />
function setupGame()<br />
{<br />
alert('this is a test');<br />
}<br />
<br />
The line we added will simply pop up a test message when the page loads. Reload '''game.html''' page to make sure it works.<br />
If everything is working you'll see a message popup when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
'''setup the random number'''<br />
<br />
Also notice that the '''behavior.js''' has a variable called '''randomNumber''' declared at the top. Unfortunately, it<br />
doesn't help us at all, because it's not set to anything yet. Woudn't it would helpful if our '''setupGame''' function<br />
set that variable to a random number? I have created a function called '''getRandomNumber''' that returns a random number.<br />
Call the function and set the return value equal to the '''randomNumber''' variable.<br />
<!--<br />
function setupGame()<br />
{<br />
randomNumber = getRandomNumber();<br />
}<br />
<br />
All you need to do is call '''getRandomNumber''' by using the function name with parentheses after it and store the return<br />
value in the '''randomNumber''' variable.<br />
--><br />
<br />
=== Step 4 ===<br />
<br />
'''create a guess function'''<br />
<br />
Earlier, I said we would be using the ids on the html elements in our JavaScript. In this step we will be finding the button<br />
on the page using JavaScript and then setting the button up so that when it's clicked on, it will call a function. <br />
<br />
First, create a function called '''guess'''. This will be the function that we'll use to take a guess at what the number is.<br />
We want this function to get called the user clicks the guess button. For now, put in another test alert, so that we can <br />
test to make sure the function is getting called when we click the button. <br />
<!--<br />
function guess()<br />
{<br />
alert('test');<br />
<br />
return false;<br />
}<br />
--><br />
<br />
'''make the guess button work'''<br />
<br />
Now, we can find the guess button and make it so that when you click on the guess button the guess function gets called.<br />
JavaScript has a function called '''document.getElementById()'''. You use this function to find html elements on the page using<br />
the id that you gave them. For example, this is how you would find the guess button and store it in a variable:<br />
<br />
var guessButton = document.getElementById("guess");<br />
<br />
The '''document.getElementById()''' function takes in one parameter, which is the id of the element you want to find. If you<br />
look at the html for the project again, you can see that there is only on html tag that has the id '''guess'''. The element<br />
with the id of '''guess''' is the one that the call to '''document.getElementById("guess")''' finds. <br />
<br />
Once the button is found, it gets stored in the variable called '''guessButton'''. We can use the variable to make the button<br />
do something when it's clicked on. To do this, we'll use something called an event handler. We'll talk about event handlers <br />
more in depth in another class. This week I just want to you set the '''onclick''' handler to your guess function, so that when<br />
the button gets clicked, the '''guess''' function gets called.<br />
<br />
You've already seen how to find the guessButton. The next code example shows you how to set the onclick handler on the button<br />
you've found:<br />
<br />
guessButton.'''onclick''' = guess;<br />
<br />
The line of code is simply saying: ''when a user clicks '''guessButton''' call the '''guess''' function''. Take the 2 lines<br />
that find the button and set the handler and put them in your setupGame function, so that they look like this together:<br />
<br />
var guessButton = document.getElementById("guess");<br />
guessButton.onclick = guess;<br />
<br />
You can also remove the test alert in the '''setupGame''' function. We won't need it anymore. If you've done everything <br />
correctly, you should be able to reload the page and then click on the guess button. When you click on it, you should see an<br />
alert box that pops up. <br />
<br />
=== Step 5 ===<br />
<br />
'''find the message area'''<br />
<br />
For the next step, you want to make it so the guess function updates the message area when the button is clicked. For now,<br />
we'll just send a test message to the message area. First, remove the any other code you have in the guess function already.<br />
<br />
If you look at the HTML for the page, you'll see that the the message area has an id of '''message-area'''. Update the <br />
guess function so that it finds the element for '''message-area''' and stores it in a variable called '''messageArea'''.<br />
<!--<br />
var messageArea = document.getElementById("message-area");<br />
--><br />
<br />
'''change the html for the message area'''<br />
<br />
One you've found the message area and stored it in a variable called '''messageArea''', it's easy to modify the HTML that's <br />
inside of the message area using JavaScript. Every HTML element allows you to modify the HTML by setting '''innerHTML'''<br />
equal to something. For example, this is how you would update the content for '''messageArea''' to say "hello!":<br />
<br />
messageArea.innerHTML = "hello!";<br />
<br />
Update the guess function so that it uses the '''messageArea''' variable to change message area html to say<br />
"the guess button was clicked!".<br />
<br />
If you've done everything correctly, you should see the message area quickly show your message, and then reload the page. <br />
The page is reloading, because the button you're clicking is automatically causing the form to reload the page. The way<br />
to fix this is to put '''return false;''' at the end of your function. Now, when you click the button, you'll see the message,<br />
but your page won't reload.<br />
<br />
If you change the onclick on any elements that will cause the browser to take action, like a button or a link, you need to<br />
'''return false''' from the function that gets called when you click. This will tell the browser that you don't want the <br />
browser to follow the link or continue with what the button was supposed to do. Don't worry about why this works for now,<br />
just know that returning false will let you have full control over the event that you're trying to attach a function to.<br />
<!--<br />
function guess()<br />
{<br />
var messageArea = document.getElementById("message-area");<br />
messageArea.innerHTML = "The guess button was clicked!";<br />
<br />
return false;<br />
}<br />
--><br />
=== Step 6 ===<br />
<br />
'''check the user's guess'''<br />
<br />
The last thing we need to do is have the game check what the user's guess was. I've already created a function that returns<br />
the user's guess for you. It's called '''getUserNumber()''' and when you call it, you get the number that the user entered <br />
in the textbox before they hit the guess button. <br />
<br />
'''check if the random number is higher than the user's guess'''<br />
<br />
We want to give the user a message that tells them if their guess was lower or higher than the random number. We can use<br />
the comparison operators from last week to check the user's number versus the random number that the computer picked. <br />
For example, the following code will check if the number they user guess was higher and show them a message:<br />
<br />
if (randomNumber > getUserNumber())<br />
{<br />
messageArea.innerHTML = "It's higher!";<br />
}<br />
<br />
The if statement compares the '''randomNumber''' variable to the value from '''getUserNumber()''' using the greater than operator.<br />
It's asking '''is randomNumber greater than getUserNumber's return value?''' And if the answer to that question is true, it's<br />
setting the HTML for '''messageArea''' to "It's higher!".<br />
<br />
Right now, the code only checks if the number is higher. You can use another if statement to check if the random number is <br />
lower than the user's number. But, let's use an '''else if''' statement instead, so we can chain a few things together:<br />
<br />
if (randomNumber > getUserNumber())<br />
{<br />
messageArea.innerHTML = "It's higher!";<br />
}<br />
else if (randomNumber < getUserNumber())<br />
{<br />
messageArea.innerHTML = "It's lower!";<br />
}<br />
<br />
Now, the code will also check if random number is lower and send the user a message that says "It's lower!" if it is. The code<br />
after the '''else if''' will only run if first if statement didn't run. <br />
<br />
Finally, we can add an extra '''else''' statement that will tell the user that they guessed the number correctly. What would<br />
that code look like?<br />
<!--<br />
if (randomNumber > getUserNumber())<br />
{<br />
messageArea.innerHTML = "It's higher!";<br />
}<br />
else if (randomNumber < getUserNumber())<br />
{<br />
messageArea.innerHTML = "It's lower!";<br />
}<br />
else<br />
{<br />
messageArea.innerHTML = "You got it!";<br />
}<br />
--><br />
<br />
=== Assignment ===<br />
<br />
Your assignment for this week is to complete the activity above and turn it in by Saturday, September 3rd at 10pm.<br />
<br />
[[Category:Introduction to JavaScript Fall 2009]]</div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2009_Class_4&diff=17725Introduction to JavaScript Fall 2009 Class 42010-09-28T22:41:05Z<p>Matthew.ephraim: </p>
<hr />
<div>== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles.<br />
<br />
== Coding Style ==<br />
<br />
One thing that I haven't talked about yet is coding style. Like the English language, JavaScript has it's own<br />
styles that you should follow if you want to make your code readable for others (and, of course, for yourself).<br />
<br />
The [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] is a comprehensive<br />
list of rules that you should try to follow when writing JavaScript. Some of the rules are more important than others,<br />
and many of them might not make sense yet for a beginner class. I've listed a few of the rules that apply for this<br />
class so far.<br />
<br />
=== Variables and Functions ===<br />
<br />
'''Clear Naming'''<br />
<br />
Your variables and functions should have names that ''clearly indicate'' what the variable is being used for or what<br />
the function does. For example, the following variable is being used to store a person's name:<br />
<br />
var '''n''' = "Matthew Ephraim";<br />
<br />
This is a bad variable name, because '''n''' doesn't tell you anything about what the variable is used for, so it <br />
might be confusing later on. A much better name would look like this:<br />
<br />
var '''name''' = "Matthew Ephraim";<br />
<br />
This name is better because '''name''' tells you what the variable is being used for.<br />
<br />
'''Multiple Word Names'''<br />
<br />
When your variable or function names have multiple words in them, it's JavaScript style to use '''camel case (aka camelCase)'''<br />
to indicate that the variable names are multiple words. For example, this variable name is made up of 2 words:<br />
<br />
var '''professorname''' = "Matthew Ephraim";<br />
<br />
It's 2 words, but it's also difficult to read. It can be made clearer by using camel case:<br />
<br />
var '''professorName''' = "Matthew Ephraim";<br />
<br />
Notice that the N is capitalized now. This makes it easier to see where the 2 words are separated. Variables names can't have <br />
spaces in them, so this is a simple way to still use 2 words in the variable name. Longer variables names with multiple words<br />
can be used as well:<br />
<br />
var '''professorFullName''' = "Matthew Ephraim"; // professor full name, 3 words<br />
var '''firstClassStartTime''' = "6:30pm"; // first class start time, 4 words<br />
<br />
=== Indentation ===<br />
<br />
Another important coding style is using proper indentation in your code. Just like indenting the first sentence of a paragraph<br />
can make text easier to read, indenting your code properly can make it easier to read as well. Typically, when you switch<br />
to a new ''block'' of code, you should indent 2 spaces.<br />
<br />
Remember that, in JavaScript, bocks are sections of code that are surrounded by { curly brackets }. So, every time you're using<br />
an opening curly bracket, you should indent 2 spaces. The code example below doesn't use any indentation:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easy to read? How about if it was indented:<br />
<br />
function alertMatt() {<br />
if (name === "Matt") {<br />
alert('hello Matt');<br />
} else {<br />
alert('You're not Matt!');<br />
}<br />
}<br />
<br />
Is this code easier to read? The code that goes with the function is indented several spaces, and the code that's associated<br />
with the if statement and with the else statement is also indented several spaces more. Most good text editors should have <br />
a feature that help you properly indent your code.<br />
<br />
== Coding Style Links ==<br />
<br />
* [https://developer.mozilla.org/en/docs/Javascript_Style_Guide Mozilla JavaScript Style Guide] <br />
* [http://www.chromeexperiments.com/ Chrome Experiments]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== JavaScript Event Links ==<br />
<br />
In addition to the wiki, you may find these links helpful<br />
<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<!--<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
--><br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
<!--<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
--><br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<!--<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<!--<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
--><br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
<!--<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
--><br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<!--<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
--><br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
--><br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
--></div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_4&diff=17724Introduction to JavaScript Fall 2010 Class 42010-09-28T21:59:46Z<p>Matthew.ephraim: Created page with '== Introduction == Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused throughout your page. This week, I will explain JavaSc…'</p>
<hr />
<div>== Introduction ==<br />
<br />
Last week, I showed you how you can wrap chunks of JavaScript code up into functions that can be reused<br />
throughout your page. This week, I will explain JavaScript events and show you how you can tie JavaScript<br />
functions to different user events that happen on your page.<br />
<br />
I will also show you how you can change an element's HTML and even change an element's styles. <br />
<br />
== JavaScript Event Links ==<br />
* [http://www.w3schools.com/js/js_events.asp JavaScript events]<br />
* [http://www.quirksmode.org/js/introevents.html quirksmode introduction to JavaScript events]<br />
* [http://www.quirksmode.org/dom/events/index.html event compatibilty tables]<br />
<br />
== Finding Elements ==<br />
<br />
Before we can start capturing events and writing our own code to handle those events, we need to be able to find<br />
the elements that we want to attach event handlers to. Let's say you have a ''div'' on the page and you give it an<br />
id of '''clickableDiv''':<br />
<br />
&lt;div id=&quot;clickableDiv&quot;&gt;&lt;/div&gt;<br />
<br />
If you wanted to find the div and store it in a variable, you would use the '''document.getElementById''' function:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
If the div was found, the function returns the element. Later on, you can use the '''clickableDiv''' variable to<br />
attach events to the element.<br />
<br />
== Events ==<br />
<br />
In JavaScript, events are ''raised'' when a user takes some action on the page. For example, a user clicking on<br />
link would ''raise'' the '''onclick''' event on the element that the user clicked on. Without JavaScript, the user<br />
interacts with the page and the browser handles any events that the user might raise. Many times, the browser's<br />
way of handling the events is just fine. Other times, there may be more interesting things that we can do with<br />
JavaScript by capturing the events and handling them in a different way than the browser would handle the events.<br />
<br />
What kind of ''actions'' from the user are considered events though? It depends on the browser, but, for the most part<br />
there is a core set of events that the majority of browsers will support. So, for example, a user might click on an element<br />
on the page. If the element is a ''button'', the browser will submit a form. If the element is an ''anchor'',<br />
the browser will go to the page that the anchor links to. Or maybe the user just clicked on a ''div'' element.<br />
In that case, the browser probably wouldn't do anything. Not unless we add some JavaScript.<br />
<br />
=== Setting Events ===<br />
<br />
So, let's take the div from above:<br />
<br />
var clickableDiv = document.getElementById('clickableDiv');<br />
<br />
We now have the div stored in a variable called '''clickableDiv'''. Let's say we wanted to have a function that handled<br />
the event that was raised when the user clicked on '''clickableDiv'''. First, we should create a function that will be used<br />
to handle the event. Let's call it '''handleClick'''.<br />
<br />
function handleClick() {<br />
console.log('hello');<br />
}<br />
<br />
The function will write message that says "hello" to the Firebug console when it is called. Let's make it so that the function is<br />
called when the user clicks on '''clickableDiv'''. To do this, we'll need to use the '''clickableDiv''' variable that we<br />
the element by adding a '''dot (.)''' after the variable name and then the name of the attribute. In this case, we<br />
want to modify the '''onclick''' attribute of the element, and set it to the name of the new function that we created:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
Notice that we used the clickableDiv variable and we added '''.onclick''' after it and then set it equal to handleClick.<br />
Attributes of elements work like variables, we can set them with the equals sign and even use them for comparisons later on.<br />
<br />
=== Other Events ===<br />
<br />
We already set the '''onclick''' event, but there are other events that we could have set as well. For example, if we wanted to<br />
call a function when the user pressed their mouse button down we could add a handler for the '''onmousedown''' function.<br />
When the user released the mouse button, we could capture the '''onmouseup''' function:<br />
<br />
clickableDiv.onmousedown = handleMouseDown;<br />
clickableDiv.onmouseup = handleMouseUp;<br />
<br />
Or maybe we want to capture the event that happens when the user moves their mouse over an element ('''onmouseover''') or maybe<br />
when a user doubleclicks ('''ondblclick''') their mouse:<br />
<br />
clickableDiv.onmouseover = handleMouseOver;<br />
clickableDiv.ondblclick = handleDoubleClick;<br />
<br />
There are some events that apply to all elements on the page and other events (like '''onchange''') that apply specifically to<br />
HTML form elements. For a comprehensive list of events and which browsers support each of them, see<br />
[http://www.quirksmode.org/dom/events/index.html here].<br />
<br />
=== the window.onload Event ===<br />
<br />
One issue that you will run into when attaching events with JavaScript is that the code to attach your events often runs before<br />
the whole page has actually loaded. This can happen if you include your JavaScript in the ''head'' tag of your page. The browser<br />
will load the JavaScript as soon as it encounters your ''script'' tag, but the rest of the page stil needs to load before you can <br />
start attaching events to elements.<br />
<br />
A common solution to this problem is to attach an event to the window's '''onload''' event. Every page has a '''window''' object<br />
that represents the current browser window. When the page loads, the browser will raise the window's '''onload''' event, which you<br />
can attach a handler function to.<br />
<br />
So, let's say you want to run a function called '''setup''' when the page loads. You can attach the '''setup''' function to onload <br />
event like this:<br />
<br />
function '''setup'''() {<br />
// do some setup stuff<br />
}<br />
<br />
'''window.onload''' = '''setup''';<br />
<br />
Any JavaScript that gets called in the setup function will be called after the page has loaded. So, you should have access to all<br />
of the elements on the page.<br />
<br />
=== this Keyword ===<br />
<br />
There is a special keyword in JavaScript that I haven't mentioned yet, and you can start taking advantage of it now that you've<br />
starting to use events. JavaScript has a special keyword called '''this''' that behaves in different ways, <br />
depending on where you use it. It's often confusing, but when used with events, it's fairly straightforward. <br />
Let's say that we used the following code to set an onclick handler for an element:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
alert(this);<br />
}<br />
<br />
The code looks fairly simple: it adds '''handleClick''' as an onclick handler for clickableDiv. '''handleClick''' gets called<br />
when the user clicks on the div and the fuction alerts the user. But what does the user see when they get alerted? If you tried<br />
to run this code, you would probably see something like the text below when you click on the div:<br />
<br />
object HTMLDivElement<br />
<br />
The message you are getting from the browser is telling you that '''this''' is pointing to a div element on the page. But which<br />
div element? It's the same one that clickableDiv points to and the same element that you clicked on. In other words, '''this'''<br />
is a special keyword that points to the element that has the event handler attached to it.<br />
<br />
The '''this''' keyword can come in handy because it will always give you a reference to the element that raised an event. It's<br />
like having a variable that automatically gets created for the element. That way, you don't need to use document.getElementById<br />
because '''this''' already gives you a reference to the element.<br />
<br />
== Modifying Elements ==<br />
<br />
Handling events isn't the only thing you can do with elements on your page. Once you've found an element on the page you can<br />
modify the element in many different ways. Two of the simplest things you can do to an element is change the HTML inside of<br />
an element and change the styles applied to an element.<br />
<br />
=== Changing the HTML ===<br />
<br />
Once again, we'll use the clickableDiv variable from above. Let's say that we wanted to change the content inside of clickableDiv<br />
to say "hello" when the div was clicked on. To do this, we would need to change the '''innerHTML''' of clickableDiv. Nearly all <br />
elements have an '''innerHTML''' attribute that references the HTML inside of the element. We can use '''innerHTML''' to see<br />
the content inside of the element or we can set '''innerHTML''' to a new value to change the content inside of the element to<br />
something new.<br />
<br />
We can create a new handler that uses the '''innerHTML''' attribute of clickableDiv to modify the content:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
clickableDiv.innerHTML = "hello";<br />
}<br />
<br />
Setting the innerHTML attribute of clickableDiv changes the content to say "hello". Notice that we used the '''clickableDiv'''<br />
variable to make these changes. There's another way that we could get access to the element that clickableDiv is pointing to.<br />
Remember the '''this''' keyword from above? This version of the '''handleClick''' will do the same thing as the one above,<br />
but it uses the '''this''' to reference the element instead:<br />
<br />
clickableDiv.onclick = handleClick;<br />
<br />
function handleClick() {<br />
this.innerHTML = "hello";<br />
}<br />
<br />
Whenever possible, use '''this''' to reference the element that raised the event from the user.<br />
<br />
=== Changing the Styles ===<br />
<br />
'''Changing Styles Directly'''<br />
<br />
An element's HTML isn't the only thing that you can change with JavaScript. You can also change an element's styles as well.<br />
For example, we might want '''clickableDiv''' to have a green border when a user puts their mouse over the div. We might also<br />
want any text inside of it to turn green. We could add a '''onmouseover''' handler that captures the event when a user puts<br />
their mouse over an element. The handler could use the the element's '''style''' attribute to gain access to the element's<br />
css styles and then modify the element's border and font color:<br />
<br />
clickableDiv.onmouseover = handleOver;<br />
<br />
function handlerOver() {<br />
this.style.border = "1px solid green";<br />
this.style.color = "green";<br />
}<br />
<br />
Every element has a collection of styles that are stored under the style attribute. Most of these styles have the same name<br />
as their matching css styles. So, any style that you could set with CSS you can also set with JavaScript by using the<br />
'''style''' attribute. When you modify an element's style, the browser will immediately display your changes.<br />
<br />
'''Changing the Class Name'''<br />
<br />
Above, we changed 2 styles on the element. More complex actions might involve a lot more typing and possible a lot more <br />
repetition. How might we have handled the styles above by using CSS? We probably would have created a class that wrapped<br />
up all of the styles:<br />
<br />
.highlighted {<br />
border: 1px solid green;<br />
color: green;<br />
}<br />
<br />
The stylesheet is where styles belong, so it makes the most sense to put the styles there. Once we have the styles, we can<br />
take advantage of them in our JavaScript. Just like every element has style attribute with a collection of styles stored under<br />
it, every HTML element has a '''className''' attribute that can be set by JavaScript. So, instead of setting the CSS styles<br />
manually, the onmouseover handler from above can use '''className''' attribute to set a new class on the element:<br />
<br />
function handlerOver() {<br />
this.className = "highlighted";<br />
}<br />
<br />
Changing the style of the element in this way keeps the styles for the page separated from the behavior and keeps your JavaScript<br />
much more compact.<br />
<br />
== Activity ==<br />
<br />
In this activity we will create a 3 number combination lock. We will use a variable to store the combination that opens the lock. <br />
We will then use HTML, CSS and JavaScript to build an interface that represents the numbers for the lock and the latch for the<br />
lock.<br />
<br />
A user should be able to enter the combination and open the lock. If the user hasn't entered the combination correctly yet, the <br />
lock shouldn't open. Once the lock has been opened, the user should be able to close it again and have the combination numbers<br />
get reset.<br />
<br />
=== Step 1 ===<br />
<br />
Download the template for the lock [http://www.mattephraim.com/intro_to_javascript_fall_2010/class_4/lock.zip here]. I have already created a simple template for the lock<br />
numbers and the lock. Unzip the template and place the whole folder of documents on your desktop.<br />
''Make sure that all of the documents are in the same folders that they were in when they were inside of the zip file.''<br />
We will start by editing the '''behavior.js''' file inside of the JavaScript folder.<br />
<br />
=== Step 2 ===<br />
<br />
I've given a function called '''setup''' to start with. The first thing you need to do is add a line of code that will make<br />
the function run as soon as the ''page loads''.<br />
<!--<br />
'''Solution'''<br />
<br />
window.onload = setup;<br />
--><br />
<br />
If you've done it correctly, you should see an alert that says "hi" when you reload the page.<br />
<br />
=== Step 3 ===<br />
<br />
Notice that there is a list of variables at the top of file. There are 4 variables that will be used to hold on to the elements<br />
on the page. Modify the setup function so that instead of alerting the user it uses the id attribute to find the each of the<br />
elements for numbers and the element for the lock. The function should store the elements in the variables that were created<br />
at the top of the page.<br />
''Make sure that you find the elements inside of the setup function though. The JavaScript won't be able to find the elements until the page has loaded''<br />
<br />
<!--<br />
'''solution'''<br />
<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box2 = document.getElementById('number2');<br />
box3 = document.getElementById('number3');<br />
lock = document.getElementById('lock');<br />
}<br />
--><br />
<br />
=== Step 4 ===<br />
<br />
Now that we've found the number elements, we need to find add some functionality so that the numbers do something when a user<br />
clicks on them. We will eventually make the numbers change when the user clicks on them, but, first, let's just make a function<br />
that handles the clicks and tie the function to the elements.<br />
<br />
Call the function '''changeNumber''' because it will eventually change the number inside of the box. Then use the '''onclick'''<br />
event handler to tie the function to each of the 3 box elements. Remember that setting '''onclick''' equal to a function<br />
will make it so that the function gets called when the user clicks the element.<br />
<br />
You can test to make sure that your '''changeNumber''' function is getting called correctly by putting a call to alert<br />
inside of it. If you've set everything correctly you should see an alert when you click on one of the boxes.<br />
<!--<br />
'''solution'''<br />
<br />
// Sets ups the lock<br />
function setup() {<br />
box1 = document.getElementById('number1');<br />
box1.onclick = changeNumber;<br />
<br />
box2 = document.getElementById('number2');<br />
box2.onclick = changeNumber;<br />
<br />
box3 = document.getElementById('number3');<br />
box3.onclick = changeNumber;<br />
}<br />
<br />
function changeNumber() {<br />
alert('test');<br />
}<br />
--><br />
<br />
=== Step 5 ===<br />
<br />
The next thing we need to do is make the numbers count up when the user clicks on the boxes. The first number in each box<br />
is 0. We will need to find this number and add 1 to it.<br />
<br />
First, let's see if we can find the current number. Remember that you can access the HTML of an element by using the '''innerHTML'''<br />
attribute of the element. We used the same onclick handler for all of the elements though. How do we know which element<br />
to find the HTML for when a user's clicks a box? See if you can modify '''changeNumber''' function so that it alerts the<br />
number inside of the box that was clicked.<br />
''Hint: remember how you can use the '''this''' keyword to find the element that raised the event''.<br />
<!--<br />
'''solution'''<br />
function changeNumber() {<br />
alert(this.innerHTML);<br />
}<br />
--><br />
<br />
=== Step 6 ===<br />
<br />
Now that you know how to get the number from the box you can change the function so that it adds 1 to the number and resets<br />
the HTML for the element to the new number. <br />
<br />
The first thing you'll want to do is store the number in a variable called '''currentNumber'''. Then, once you have the number<br />
you can add 1 to it. Do you remember a shorthand we used last week to add 1 to a number?<br />
<br />
Once you've added 1 to the number, you need to set the HTML of the element so that it matches the new number. Use the<br />
'''innerHTML''' attribute again. This time use it to set the value of the new HTML.<br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
currentNumber++;<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
If things are working correctly the number inside of each box should go up by 1 when you click the box.<br />
<br />
=== Step 7 ===<br />
<br />
You'll probably notice one problem with the way the numbers work right now: when you click the numbers, they just keep counting<br />
up. What we really want is for the boxes to count up to 9 and then go back to zero if the user clicks again. <br />
<br />
Modify the '''changeNumber''' function so that it checks if the current number is ''less than'' 9 and adds 1 to it if it is.<br />
Otherwise, the function should set the number back to 0. <br />
<!--<br />
'''solution'''<br />
<br />
function changeNumber() {<br />
var currentNumber = this.innerHTML;<br />
if (currentNumber < 9) {<br />
currentNumber++;<br />
}<br />
else {<br />
currentNumber = 0;<br />
}<br />
<br />
this.innerHTML = currentNumber;<br />
}<br />
--><br />
Now, when you click on the numbers they should count up to 9 and then go back to 0.<br />
<br />
=== Step 8 ===<br />
<br />
The numbers for the combination lock are now working correctly. The next step is to allow user to click the lock image. Add a new<br />
function called '''checkLock''' that will eventually be used to check if the lock should open. Go back to the setup function<br />
and add an '''onclick''' handler to the lock so that the '''checkLock''' function gets called when user clicks on the lock.<br />
<br />
Again, you can check to make sure that you function works by adding an alert to the function.<br />
<br />
<!--<br />
'''solution'''<br />
<br />
lock = document.getElementById('lock');<br />
lock.onclick = checkLock;<br />
<br />
function checkLock() {<br />
alert('test');<br />
}<br />
--><br />
<br />
=== Step 9 ===<br />
<br />
Now we need to check to make sure the user has correctly entered the combination for the lock and then do something if they have.<br />
The user's combination will be made up of the HTML that is currently inside of each of the elements. You can store the HTML for<br />
all 3 of the box elements in an variable like this:<br />
<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
<br />
The '''combination''' variable should now be a string equal to the HTML for all 3 box elements. So, if the boxes are all set to 3,<br />
'''combination''' will be "333".<br />
<br />
Write some code that checks if '''combination''' is equal to the '''COMBINATION''' variable that represents the actual combination<br />
for the lock. Alert the user if the combinations are equal to each other.<br />
<!--<br />
'''solution'''<br />
<br />
function checkLock() {<br />
var combination = box1.innerHTML + box2.innerHTML + box3.innerHTML;<br />
if (combination === COMBINATION) {<br />
alert('hello');<br />
}<br />
}<br />
--><br />
<br />
=== Step 10 ===<br />
<br />
Instead of alerting the user when the combination is correct, we want to change the lock image to one that represents an unlocked<br />
lock. When you have an image element, you can change the source for the image by modifying the '''src''' attribute. The<br />
'''checkLock''' function handles '''onclick''' for the lock image, which means that '''checkLock''' should have access to the <br />
lock image through the '''this''' keyword. Use '''this''' to change the '''src''' for the image to "images/unlocked.png" when<br />
the user clicks the lock and the combination is correct.<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
}<br />
--><br />
<br />
=== Step 11 ===<br />
<br />
We now have a lock that opens, but there is no way to close the lock once it has been opened. It would be nice if we had the ability<br />
to lock the lock again.<br />
<br />
One thing that we should keep track of is whether or not the lock has been unlocked. Add variable to the top of the page called<br />
'''unlocked''' and make sure the variable is set to '''false''' to start with:<br />
<br />
var unlocked = false;<br />
<br />
In the '''checkLock''' function set this new variable equal to true at the same time that you change the lock image. Now we have<br />
a way of keeping track of if the lock is still locked or not.<br />
<br />
<!--<br />
'''solution'''<br />
if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
<br />
=== Step 12 ===<br />
<br />
Now that we can check if the lock is locked or not, we can close the lock and reset the combination if the user clicks on a lock<br />
that has already been opened. To do this, we need to modify the '''checkLock''' function so that it first checks if the lock has<br />
already been unclocked. If it's already been unlocked it should alert the user and say "already unlocked!". Otherwise, it should<br />
do what it did before and unlock the lock.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
unlocked = false;<br />
this.src = "images/locked.png";<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
--><br />
<br />
=== Step 13 ===<br />
<br />
Finally, let's write a function that resets the lock back to locked and sets all the numbers back to 0. Call the new function<br />
'''reset'''. This new function should modify the innerHTML for box1, box2, and box3, so that they are all equal to 0 again. It<br />
should also modify the '''src''' on the lock element so that it's equal to "images/locked.png" again. And finally, it should<br />
set the '''unclocked''' variable back to false again.<br />
<br />
In the '''checkLock''' function you should call the '''reset''' function if the lock has already been unlocked.<br />
<br />
<!--<br />
'''solution'''<br />
if (unlocked) {<br />
reset(); // a new function you need to define<br />
} else if (combination === COMBINATION) {<br />
this.src = "images/unlocked.png";<br />
unlocked = true;<br />
}<br />
<br />
// Define this function somewhere<br />
function reset() {<br />
unlocked = false;<br />
lock.src = "images/locked.png";<br />
box1.innerHTML = "0";<br />
box2.innerHTML = "0";<br />
box3.innerHTML = "0";<br />
}<br />
--></div>Matthew.ephraimhttps://imamp.colum.edu/mediawiki/index.php?title=Introduction_to_JavaScript_Fall_2010_Class_2&diff=17681Introduction to JavaScript Fall 2010 Class 22010-09-21T22:55:25Z<p>Matthew.ephraim: /* Today's Interesting JavaScript Site */</p>
<hr />
<div>[[Introduction_to_JavaScript_Fall_2010|Back to Introduction to JavaScript Fall 2010]]<br />
<br />
== Introduction ==<br />
<br />
This week, I'll be covering the most basic aspects of JavaScript. In short, this is what you'll need<br />
to get up and running. If you have any experience with JavaScript, you are probably already familiar with<br />
most of what I'm going to cover this week. However, I think there are some bad practices that get propagated<br />
by many (let's say most) JavaScript introductions. I'll talk about not only what you should do, but also<br />
what you '''shouldn't''' do when writing JavaScript.<br />
<br />
== Browser Based JavaScript ==<br />
<br />
The first thing I want to make note of is that this class will focus on JavaScript being run in the browser.<br />
This is probably the only type of JavaScript that most people have been exposed to. However, there are a<br />
significant number of other applications for JavaScript that do not rely on running in the browser.<br />
We probably won't get into those applications in this introductory class, but many of the concepts learned<br />
in this class will apply to both browser based and non-browser based JavaScript.<br />
<br />
== Including your JavaScript ==<br />
<br />
The first thing that you need to do when writing JavaScript for the browser is include the script on your webpage.<br />
As you may already know, JavaScript is included on the page using the &lt;script&gt; tag. Unfortunately, it's not<br />
quite as simple as that. There are several ways of using the &lt;script&gt; tag and some ways have advantages<br />
over others.<br />
<br />
=== A Basic Script Tag ===<br />
<br />
Let's start with a basic script tag:<br />
<br />
&lt;script type=&rdquo;text/javascript&rdquo;&gt;<br />
// your code here<br />
alert(‘hello’);<br />
&lt;/script&gt;<br />
<br />
Nothing too complicated. The code section opens with a &lt;script&gt; tag and closes with a<br />
&lt;/script&gt;, and your code goes between the opening and closing tags. An important thing to note:<br />
the '''type''' attribute of your script tag needs to be set to '''text/javascript'''. You may notice that some browsers<br />
let you get away with not adding this attribute. Until HTML5 is more widely supported, don’t count on this being the case. <br />
Always include the '''type''' attribute.<br />
<br />
But what if you wanted to include another file that contains your JavaScript? To do this, you simply add the '''src'''<br />
attribute and set it to the name of the file that you want to include:<br />
<br />
&lt;script type=&ldquo;text/javascript&rdquo; src=&ldquo;hello.js&rdquo;&gt;<br />
&lt;/script&gt;<br />
<br />
The code for your page is no longer between the opening and closing script tags. Instead it's in the file '''hello.js''',<br />
which contains just the code for your page:<br />
<br />
// your code here <br />
alert(‘hello’);<br />
<br />
'''This last method, including the JavaScript from an external file, is the method that will use in class.'''<br />
<br />
=== Placing the Script Tag ===<br />
<br />
So now you have a &lt;script&gt; tag. But where does it go?<br />
<br />
Technically, the &lt;script&gt; tag can go anywhere in the head or the body of your page. All of these techniques<br />
will work:<br />
<br />
'''At the top of the body'''<br />
<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;script&gt;&lt;/script&gt;<br />
&lt;p&gt;some content&lt;/p&gt;<br />
&lt;/body&gt;<br />
<br />
'''Or at the bottom of the body'''<br />
<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;script&gt;&lt;/script&gt;<br />
&lt;p&gt;some content&lt;/p&gt;<br />
&lt;/body&gt;<br />
<br />
'''Or in the head of your document'''<br />
<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
&lt;script&gt;&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;p&gt;some content&lt;/p&gt;<br />
&lt;/body&gt;<br />
<br />
You may see people recommend putting the script tag at the bottom of the body. There's a good reason for this, and I will<br />
explain it later in the class.<br />
<br />
'''The last method, putting the tag in the head for the page is the one we will use for class'''<br />
<br />
=== How '''NOT''' to Include JavaScript ===<br />
<br />
There are also ways to add JavaScript that technically work, but are not recommended.<br />
'''Adding JavaScript using these techniques will be unacceptable for this class.'''<br />
Below, I have listed some of those techniques:<br />
<br />
'''Inline JavaScript Handlers'''<br />
<br />
&lt;a onclick=&ldquo;doSomething()&rdquo;&gt;Bad&lt;/a&gt;<br />
<br />
&lt;img onmouseover=&ldquo;hover()&rdquo; onmouseout=&ldquo;unhover()&rdquo; /&gt;<br />
<br />
&lt;a onclick=&ldquo;MM_badJavaScript(true)&ldquo;&gt;Bad&lt;/a&gt;<br />
<br />
'''Abusing Anchor Tags'''<br />
<br />
&lt;a href=&ldquo;javascript:void(0)&rdquo;&gt;Bad&lt;/a&gt;<br />
<br />
&lt;a href=&ldquo;#&rdquo; onclick=&ldquo;doSomething(); return false;&rdquo;&gt;<br />
<br />
I want to repeat what I said before: '''adding JavaScript using these techniques will be unacceptable for this class.'''<br />
<br />
== Progressive Enhancement and Unobtrusive JavaScript ==<br />
<br />
In the sections above, I may have sounded somewhat opinionated about the ''right'' and ''wrong'' ways to include JavaScript.<br />
In truth, some of it is opinion. After all, if the JavaScript works like you wanted, who's to say that you did it the<br />
''wrong'' way?<br />
<br />
Web development, like any profession, has it's own best practices that have developed over time. In the bad old days of the<br />
web, people where somewhat careless about how they organized their web pages. This often led to pages that were hard to<br />
maintain in the long run. Often, these pages worked great under the best of circumstances, but once one thing went wrong<br />
they fell completely apart.<br />
<br />
To help combat these types of sites, web experts decided that pages should start out with a core of solid functionality,<br />
with the fancy things added on top to enhance the user epxerience. In a nutshell, this idea is known as<br />
'''progressive enhancement'''. The following series of articles from the (fantastic) web development magazine<br />
[http://alistapart.com A List Apart] summarize the concepts, and hopefully give you an idea of why this class will follow<br />
the rules that it does.<br />
<br />
'''Progressive Enhancement Articles'''<br />
* [http://www.alistapart.com/articles/understandingprogressiveenhancement/ Understanding Progressive Enhancement]<br />
* [http://www.alistapart.com/articles/progressiveenhancementwithcss/ Progressive Enhancement with CSS]<br />
* [http://www.alistapart.com/articles/progressiveenhancementwithjavascript/ Progressive Enhancement with JavaScript]<br />
<br />
== Intro to JavaScript Syntax ==<br />
<br />
There are few fundamental pieces of JavaScript syntax that I want to make sure everyone understands before moving<br />
forward with the class. These parts are some of the commonly misunderstood or ignored parts of the JavaScript language.<br />
To be a truly great JavaScript coder, you must use the syntax elements correctly.<br />
<br />
=== The '''var''' Keyword ===<br />
<br />
The JavaScript keyword '''var''' stands for '''variable'''. Variables are a fundamental aspect of almost any programming language.<br />
Variables let you take a value and give it a special name that you can reuse throughout the program, instead of having to<br />
use the original value.<br />
<br />
Maybe, I have a result of a math calculation that I want to hold on to<br />
<br />
'''var''' result = 42 + 567 / 99 + 40;<br />
<br />
'''result''' holds on to the result of the calculation so that I can use it later.<br />
<br />
Notice that I put '''var''' before the name of the variable. In an ideal world, I would be required to use the world<br />
'''var'''. However, JavaScript is perfectly happy to let me do this:<br />
<br />
result = 42 + 567 / 99 + 40;<br />
<br />
While this technically works, it doesn't mean exactly the same thing as the version with the '''var''' keyword. This time<br />
'''result''' is "global" variable. Meaning that it's available throughout my entire program. This means that I can never<br />
predictably use a variable called '''result''' again, because '''result''' in one area of the code might clash with the other<br />
'''result''' variable and cause strange errors.<br />
<br />
There are ways around this issue. Always using the '''var''' keyword is the first step. The rest of the steps will become<br />
more obvious when we start to talk about functions.<br />
<br />
=== ; (aka, the Semicolon) ===<br />
<br />
In JavaScript, much like the English language, the semicolon is often ignored. Unlike English, however,<br />
ignoring the semicolon can cause serious problems.<br />
<br />
Take this piece of code for example:<br />
<br />
// Some info about John;<br />
var firstName = &ldquo;John&rdquo;;<br />
var lastName = &ldquo;Lennon&rdquo;;<br />
<br />
// Some info about the band<br />
var band = &ldquo;Beatles&rdquo;;<br />
<br />
It's some fairly simple code, and it uses a semicolon at the end of each line to separate statements. Technically,<br />
the code could have been written this way, without the semicolons:<br />
<br />
// Some info about John;<br />
var firstName = &ldquo;John&rdquo;<br />
var lastName = &ldquo;Lennon&rdquo;<br />
<br />
// Some info about the band<br />
var band = &ldquo;Beatles&rdquo;<br />
<br />
Odds are, the code would still work. So what's the problem?<br />
<br />
One potential problem has to do with how JavaScript statements are separated. In this case, each statement is<br />
on its own line. When you move to a new line, JavaScript usually considers this to be a new statement. So,<br />
without a semicolon, the code still works. JavaScript knows that you meant to move to a new line. But, with a large<br />
amount of code, these extra lines (not to mention extra comments) can take up a lot of space, which amounts to<br />
longer download times for the user.<br />
<br />
One solution to this problem with large amounts of code is to ''"pack"'' or ''"minify"'' the JavaScript. When you pack your<br />
JavaScript, you use a special tool that will compact the JavaScript, removing comments, extra whitespace and line breaks.<br />
The programmer will still use the original code with the formatting that's optimized for humans, but the final<br />
code will be packed before it's sent to the user, which can speed up download times.<br />
<br />
Let's pack the simple code from above:<br />
<br />
var v1=&ldquo;;John&rdquo;;var v2=&ldquo;Lennon&rdquo;;var v3=&ldquo;Beatles&rdquo;;<br />
<br />
No more comments, and a minimal amount of whitespace. The code still works though, because the semicolons<br />
separate the statements.<br />
<br />
But what if the semicolons are removed:<br />
<br />
var v1=&ldquo;John&rdquo;var v2=&ldquo;Lennon&rdquo;var v3=&ldquo;Beatles&rdquo;<br />
<br />
As far as the JavaScript interpreter is concerned, this is gibberish. It will simply cause an error when it loads.<br />
If the original code is significantly complex, adding in the necessary semicolons may be somewhat of large task.<br />
<br />
Packing is not the only reason to add in semicolons, but it's an example where leaving them off can cause<br />
confusion and limit the flexibility of your code.<br />
<br />
== Comments ==<br />
<br />
Comments are one piece of JavaScript syntax that are 100% meant for humans. You could write thousands of lines of JavaScript<br />
and never once write a comment. The code would work fine. Despite this, comments will be a required part of this class.<br />
<br />
Many programmers will say that you should use clear variable and function names in your code. By doing that, you will<br />
eliminate the need for comments. To a certain extent, this is true. Excessive commenting can often indicate that<br />
your code is hard to understand and badly organized. However, there are cases where comments can still provide<br />
value, even to very well written programs.<br />
<br />
Good comments are meant to clarify and describe “intent”. That is, they should describe overall ideas about the code<br />
and communicate what the programmer intended to do with the code. The comments could be for particular parts of some<br />
code or they could be part of the documentation for the overall program.<br />
<br />
Below is an example of a comment that clarifies the intent of a function. It uses '''//''' to indicate that everything<br />
else on the line is a comment and should not be read as JavaScript code:<br />
<br />
// Use makeCookies to bake a custom<br />
// amount of cookies. The maximum<br />
// number of cookies is 20.<br />
// Our cookie sheet becomes<br />
// overloaded after 20 cookies.<br />
function bakeCookies(numberOfCookies) {<br />
... some code<br />
}<br />
<br />
This function bakes some cookies. Another programmer could probably read through the code and figure out that the function<br />
limits the number of cookies to only 20. But, it's difficult to communicate why that limit is in place using only code.<br />
A comment can provide some extra information about the function that may be valuable to other programmers.<br />
<br />
Sometimes, a good comment at the beginning of a library or somewhere else in the code can provide some context, or some<br />
overall information about the code that follows. The following example uses the block comment syntax. Block comments can<br />
be on multiple lines. They begin with "/*" and end with "*/". Anything else between will be considered comments:<br />
<br />
/*<br />
This library will give you some<br />
really nifty JavaScript effects.<br />
The following functions are<br />
available inside this library.<br />
...<br />
*/<br />
<br />
This block comment might go on to describe some of the functions inside of the library and how other programmers<br />
might use them.<br />
<br />
For this class, I simply ask you to clarify your code. Make sure you name your functions and variables clearly,<br />
but when something might be clearer with a comment, be sure to add one. It’s a balance, and I don’t expect anyone<br />
to have it perfect at the beginning (or the end of the class). When in doubt, add the comment. I will be sure to let<br />
you know if I think you are using too many comments (or too few).<br />
<br />
== Primitive Types ==<br />
<br />
Every value in JavaScript has an associated “type”, which indicates what value can be used and determines the value’s<br />
behavior. JavaScript’s “primitive” types are the simplest, most basic types. Rather than reiterate the basic information<br />
about each primitive type, I recommend reading Wikipedia's<br />
[http://en.wikipedia.org/wiki/JavaScript_syntax#Primitive_data_types summary] of JavaScript's primitive types. The types that I<br />
didn't discuss in the lecture this week will be covered in a future class.<br />
<br />
== Today's Interesting JavaScript Site == <br />
<br />
[http://www.chromeexperiments.com/ Google's Chrome Experiments / Chrome Showcase]<br />
<br />
Since its introduction, Google Chrome has always been on the cutting edge of web standards and HTML5. This site is intended to show off what Google Chrome is capable of.<br />
<br />
== Activities ==<br />
<br />
=== Activity 1 ===<br />
<br />
Getting started with Firebug<br />
<br />
* '''1.''' [http://getfirebug.com/ Install Firebug]<br />
* '''2.''' Click on the little bug that appears in the bottom right corner<br />
* '''3.''' Go to [http://csszengarden the CSS Zen Garden]<br />
* '''4.''' Use Firebug to explore the page. Notice that you can select elements, see their HTML and the HTML rules applied to them. You can also change the HTML and the CSS.<br />
*'''5.''' You can also use Firebug to help figure out what's wrong with your JavaScript. I will show you some examples in class.<br />
<br />
More info:<br />
[http://code.google.com/apis/ajaxsearch/articles/firebug.html A Google tutorial on using Firebug]<br />
<br />
=== Activity 2 ===<br />
<br />
Let's create a ''very basic'' page with some JavaScript<br />
<br />
* '''1.''' Create a folder for the page called '''page''' (or whatever you want to call it)<br />
* '''2.''' Create a new document called '''content.html'''<br />
* '''3.''' Add the following code to '''content.html''' and save it:<br />
<br />
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;<br />
&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;<br />
&lt;html&gt;<br />
&lt;head&gt;<br />
<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
<br />
'''Note: make sure that there is no whitespace beforethe DOCTYPE declaration.'''<br />
'''You would be surprised (or maybe you wouldn't be) how many problems develop if you forget this rule.'''<br />
* '''4.''' Create a new folder inside of '''page''' called '''javascripts'''<br />
* '''5.''' Inside of that folder create a new file called '''behavior.js''' and add the following to it:<br />
<br />
alert('test');<br />
<br />
* '''6.''' Using the technique that was recommended for this class. Include the JavaScript file on in your page. Note that you can get to your JavaSript file by referencing it as "javascripts/behavior.js".<br />
* '''7.''' Open '''content.html''' with Firefox. If you have included your script correctly, you should get an alert message that says "test".<br />
<br />
=== This week's assignment ===<br />
<br />
There isn't a formal programming assignment for this week. I just want you to read the 3 articles<br />
that are listed under the Progressive Enhancement section. Pay particularly close attention to<br />
"Progressive Enhancement with JavaScript". Be ready to discuss the articles during next week's class.<br />
<br />
[[Category:Introduction to JavaScript Fall 2010]]</div>Matthew.ephraim