Introduction to OO and the DOM
Modern programming techniques utilize what is called Object Oriented Programming. Objects are basically self contained things that contain other things. They're Objects.
Before you create an object, you have to write a class. A class is simply the piece of code that defines what an object is and what kind of stuff you can do with it. Writing classes are a bit beyond the scope of this section. We'll just go over what an object is and how to use them.
Lets use an analogy. What's an object that everyone can relate to? How about balls? Okay, so a "ball" is an object in real life, and we'll use a "ball" as our object in programming.
Objects are made up of two types of parts: Methods and Properties. Typically, you can access an object's parts using "dot notation". Object.Method() or Object.Property ... not too hard.
A method is just a function that is owned by an object. It can either be something that the object does, or it can be something that can be done to the object.
For our example: You can kick a ball. So if kick() is a method of our ball object, and you wanted to kick the ball, you'd do ball.kick(). Balls can also explode. So, if you wanted to make the ball explode, do ball.explode().
A property is something that describes the object. Or another object that the main object owns. It's important to note that properties are not functions, so you don't put () at the end.
Back to our example: Balls might have a size. So, maybe ball.size might return "big" or "small". Also, balls might have hair. ball.hair would return a hair object.
Hair is another object, so it'd be like a 'sub-object'. Hair would probably have some methods and properties of its own. You might want to pluck one of the hairs off the ball: ball.hair.pluck(); or maybe you want to find out what color the ball's hair is: ball.hair.color might return "blonde" or "black".
So, there's your crash course in object oriented programming. We'll probably go into more details later.
Now, because we're still in the "Output" chapter, you might be wondering what these objects have to do with outputting anything. That's where we get to the DOM or Document Object Model.
Web pages are like one giant object with sub-objects and methods that can be used to manipulate the page and the objects within the page.
The top level, root object is the window. The alert() function we used earlier, is actually a method of the window object. You could, if you wanted to do window.alert("vrimples"); and get the same effect. Window is an exception, however, in that you don't have to write it everytime. It's kind of assumed.
Probably the most important property of the window is the document. Document is everything that is displayed in the window. This is where most of the good stuff goes down.
Document has a method called write(). It writes stuff to the document. Example:
<html>
<head>
<title>My First Webpage</title>
<script type="text/javascript">
document.write("VRIMPLES");
</script>
</head>
<body>
Balls!
</body>
</html>
Instead of using alert() to output "VRIMPLES", we use document.write() ... Which simply writes out "VRIMPLES" when that line is parsed.
Now, that's a good way to output stuff into a web page using javaScript, but there's another way that I prefer. It's a little more involved, but you can do a lot more with it. The following code is a modified version of our original code, but knowing what you know about objects, I think you can handle it.
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
Balls!
<div id="output"></div>
<script type="text/javascript">
document.getElementById("output").innerHTML = "VRIMPLES";
</script>
</body>
</html>
Here, we're introducing a few new elements. An important thing to remember is that each element is essentially a property or sub-object of document.
The first new thing is the <div> tag. <div> creates a new block element. It stands for "division". Div's are mainly used to create sections of HTML and divide it from other parts. Block elements are separated from the rest of the rendered html, placing a new line above and below that section.
This particular div has two properties that we play with. The first is the "id" property. Here, we're defining it inside the tag itself and, thus, is set as soon as the div is rendered. id makes it much easier to access via javascript.
The <div> is followed by the javascript. Note that we've moved the javascript down, below the <div>. This is because the <div> must be created before we can access it with the javascript. The browser parses the code from top to bottom. If we kept the javascript in the header, the browser would try to access the output <div> before it is created and would return an error. Having the javascript at the end allows it to access the div, now that it's created.
Now, the new line of javascript: document.getElementById("output").innerHTML = "VRIMPLES";
What this says is "use the getElementById method to grab the output div, then set the output div's innerHTML property to "VRIMPLES".
getElementById() is a method of document. For the most part, the pre-defined methods do exactly what the name implies. getElementById() gives you access to the element with the id specified in the parameter list. That's why we needed to specify the id in the tag itself--so that we know what element we're trying to access.
In my opinion, this is the easiest way to access elements. There are other ways to do this, utilizing different functions which "walk the object tree". I like this way, though. It's nice and simple.
So, getElementById() gives you access to the element. Basically, the code is substituting "document.getElementById("output")" with "the output div". The javascript now thinks that it's doing 'outputdiv.innerHTML = "VRIMPLES";' Of course, you can't access the 'outputdiv' directly, so this is the next best way.
The output div element has its own set of methods and properties. One of its properties is innerHTML. As you've probably guessed, it contains all the HTML that is inside the element. With this property, you can 'get' and 'set' the inner HTML.
You can set the value of a property by using the '=' operator. It's important to realize that this is really an "equals" operator, it's a "set" operator. Instead of "innerHTML equals VRIMPLES", it's more accurate to say "innerHTML is VRIPMLES" or "innerHTML becomes VRIMPLES".
What we're doing is putting the value of "VRIMPLES" into the innerHTML property of the output div. We'll be using the = operator a lot from now on.
To summarize: Create an empty <div> element with an id of "output". Using the getElementById() method, grab the div with an id of "output" and cram "VRIMPLES" into its innerHTML.
Not so hard, right?
Next time: Variables.
Wisdom Archive
- August 2008 (2)
- July 2008 (2)
- June 2008 (3)
- May 2008 (3)
- April 2008 (4)
- March 2008 (7)
- February 2008 (6)
- January 2008 (1)
- December 2007 (3)
- November 2007 (9)
- October 2007 (26)
- August 2007 (1)
- June 2007 (1)
- May 2007 (1)
- March 2007 (1)
- February 2007 (2)
- December 2006 (4)
- November 2006 (4)
- October 2006 (5)
- September 2006 (2)
- August 2006 (1)
Categories
- poonheads (22)
- music (17)
- comic (16)
- site news (12)
- coding (11)
- Classic Wisdom (10)
- video (10)
- I Love Music (9)
- javascript (9)
- photo (9)
- rant (8)
- tutorial (8)
- web design (8)
- hardware (7)
- hobby (7)
- mustaches (7)
- gear (6)
- horrifying (6)
- story time (6)
- earworm (5)
- food (5)
- art (4)
- software (4)
- Coding for Complete Noobs (3)
- movie (3)
- Captain Numbskull (2)
- Everyday Wisdom (2)
- beverage (2)
- knives (2)
- review (2)
- toys (1)
Wednesday, March 26, 2008
Coding for Complete Noobs: Chapter 2 part 2
Tuesday, February 26, 2008
Coding for Complete Noobs: Chapter 2 part 1
Chapter 2: Output
Part 1
Output is the data that is put out from the program. Go figure. The program runs and spits out the results. That's your output. It's pretty much the only way to tell if your program is doing anything. Sure, you could make a program that that counts to one thousand, but what's the point if you can't watch it count?
It's true that the plain html that we made last time is a form of output. The only problem is that it's static. You save the file and open it in the browser and it doesn't do anything except print out the contents of the file. Nothing happens.
To make the page "do stuff" we need to add in some javascript. Javascript enhances webpages with interactivity. When the user does something to the page, the javascript will do something in response. In order to let the user know that something just happened, you'll need to be able to output a message.
On with the code... We'll start with the page we created last time, but with modifications to add the javascript:
<html>
<head>
<title>My First Webpage</title>
<script type="text/javascript">
alert("Vrimples");
</script>
</head>
<body>
Balls!
</body>
</html>
You'll notice the <script> tags in the header. That's where your javascript goes. The <script> element can actually go anywhere in a page, but it's generally preferred that you keep most of the code in the header. As with all rules, however, there is a time and a place for breaking it. Sometimes it's necessary to throw a bit of javascript right in the middle of a paragraph. Just try to keep it to a minimum.
The <b>type="text/javascript"</b> part of the script tag is called an 'attribute'. It's just an extra bit of info about the element that, in this case, tells the browser that the following code is of type "text/javascript". Depending on various factors, the script may or may not work without the type attribute, so you must remember to add it in there.
Inside the script element is where the real fun begins. Instead of just marking up text, as with HTML, we'll be writing actual real code that will do stuff. This simple example simply pops up an alert box with the word "Vrimples". That's what the alert() function does. There are several other ways to output messages to the user, but we'll start with alert() because it's simple, easy to use, and will allow me to introduce a few important programming concepts.
alert() is an example of a function or method. Functions and methods are pretty much the same thing. Later on, when we get to more advanced topics, I'll explain the difference, but for the time being, just think of it as two words for the same thing.
Functions are like actions. When you call a function, the script preforms that action. I like to think of functions as the 'verbs' of programming.
Each function has several parts. In our example, "alert" would be the function name. That's simple enough, right? The name is always followed by a pair of parentheses (). That's how the program knows that it's a function. If you don't put the parentheses, the browser will not treat it as a function and may return an error.
Inside the parentheses is the parameter list. Parameters are bits of information that you pass to the function. The function will take this information and manipulate it or use it for calculations or for whatever it is that the function does.
In this case, alert() only takes one parameter. "Vrimples". "Vrimples" is a <b>string</b>. A string is a group of individual characters that are lumped together with quotation marks. In javascript, you can use either single quotes (') or double quotes ("). You just have to make sure that you use the same type of quote at the beginning and end of the string. The first quote tells the browser to start making a string and the ending one tells the browser to end the string. Other programming languages require you to only use single quotes or to only use double quotes. But since we're not worried about other languages at this point, we'll just forget about it. Just remember to remain consistent.
Something to think about: Supposed you wanted to print out a string with a quotation mark in it... for example: She said "Vrimples". You might try putting alert("She said "Vrimples""). This won't work. Why? Because the browser treats the second quotation mark as the ending mark and starts a new string at the third quotation mark. So what do you do?
You have to use the escape character. In javascript, the escape character is a backslash (\). It tells the browser "The next character after this escape character should be treated differently than it normally would be." So, you would end up with <b>alert("She said \"Vrimples\"")</b>. That way, the browser interprets only the first and last quotation marks as starting and ending the string. It simply prints out the quotes around Vrimples.
But back to our sample code... So you have the alert() function that takes one single string parameter (which, in our example, is the string "Vrimples"). The browser reads that and pops up an alert box with the text "Vrimples" in it.
This is all followed by a semicolon (;). The semicolon tells the browser that it's at the end of a command. It's kind of like a period (.) when you're writing in English. In javascript, the semicolon are optional. You could just have every line of code on a separate line and the browser would treat the line-breaks as semicolon. However, almost every other programming language I know requires you to put a semi colon at the end. Since it won't hurt anything, end every line with a semi colon. It will eventually become a habit that will transfer to other languages, should you decide to learn one.
That right there is the basic syntax of javascript. Just about everything builds on that. Of course, you'll need to do some stuff other than just popping up alert boxes. I would imagine that most tutorials and manuals and books would start talking about variables, loops, functions, and a whole lot of other important fundamentals. We'll get to that later.
My philosophy is 'learn how to do the hard stuff, then go back and learn the basics so you can make the hard stuff more awesome'. That's why in the next chapter, we're going to talk about Object Oriented Programming and The Document Object Model.
Having come this far, hopefully you're enjoying yourself and learning something. If I'm going to fast or throwing too much at you at once, I can pretty much guarantee it's only going to get worse. This here is where things start getting crazy, so hold on to your hat as we jump right in to the thick of it.
~Ben
Thursday, February 14, 2008
Coding for Complete Noobs: Chapter 1
Kids today take computers for granted. They play on the YouTube and their MySpaces and really have no idea what it takes to create such fantastic pieces of software. I do. Because I'm a programmer.
When I explain to people what it is that I do for a living, I get one of two responses. "Oh, that's nice." or "I could never do that." Sometimes both. The later of the two is not entirely true. You just need instruction from someone who can speak your language.
That's what I'm attempting to do here.
--
Before we get started, there are a few things that you should know. This first part is very long and might be kind of boring, but it's vital if you hope to understand anything further down the road.
Programming, or "coding", as we call it, is the process of writing words and numbers and symbols (or "code"). That code is run through a compiler or an interpreter which transforms the code into a program. It's just that simple.
All websites are created in such a fashion. A programmer will write code (sometimes utilizing other programs to assist in the code writing) and your web browser acts as an interpreter which translates the code into a web page. You can readily view the source code of any given page by right-clicking the page and selecting "View Source".
Technically, however, websites are not generally considered programs. Programs are created by running the source code through a compiler which produces a separate application that can be run completely independent of the compiler. Websites are interpreted, which means that the code has to be re-interpreted every time you view the page, and thus are completely dependent on the interpreter. "Programs" written in interpreted languages are typically called "scripts". I think (now, don't quote me on this) that they are called scripts, because it's like an actor reading a script and acting it out. Whatever the case, I almost always refer to web pages as simply "Web pages" or "Web sites".
So... Web pages are actually just source code that is run through a web browser which interprets the code and displays all the pretty colors and pictures and stuff. Enough of with the theory.
To create a web page, you need 3 things. A text editor (to edit the code), a web browser (to interpret the code), and a language in which to write the code.
For the text editor, you can use MS Notepad (start->programs->accessories>notepad) and for the browser/interpreter, just use whatever browser you're using to view this page.
Modern webpages utilize a series of interconnected languages to provide the rich user experience we have today. The browser itself usually only interprets 3 of them: HTML, JavaScript, and CSS. Which brings me to an interesting aside.
In web programming, there are two different types of languages: Server-side and Client-side. The server is the big computer that the company will host the site on. You're computer, or the client, will contact the server and download the webpage which is then interpreted by your browser. Server-side scripts are run on the server, before your computer ever gets them. The Server-side script (written in Perl, or PHP, or C#, or Java ) will usually do some complex calculation or database interaction that your browser is unable to do. It creates a page with only Client-side code (javaScript, HTML, CSS) and sends THAT to your browser. Your browser interprets that code and displays the page. Because you only have access to the client (your computer and your web browser) we'll be focusing on Client-side languages.
A run down of the languages that we'll be covering:
HTML: HyperText Markup Language. This is the bread and butter of web sites. If you know nothing else, you can still make a decent web site that only uses HTML. It was originally designed to mark-up text in order to link pages together. Since then, it's been expanded to include formatting tools (bold, italic, tables, etc). HTML simply tells the browser how to render the page and does not provide much interactivity besides linking to other documents and pages. The current incarnation is called XHTML. It's more strict on syntax and adds more features but is, for the most part, still static.
CSS: Cascading Style Sheets. This language is used to make pages pretty. While it is possible to change colors and fonts and stuff using HTML, CSS allows us more options and freedom in regards to formatting and styling our pages.
javaScript: Or simply "JS". Not to be confused with Java (which is a compiled language that has absolutely nothing to do with javaScript). This language provides more interactivity with web pages. Plain HTML is very static. Adding javascript can make a page very dynamic. While it's pretty easy once you know the basics, it can be VERY powerful if you use it right.
--
That was clear as mud, right? I promise, it's easier than it sounds. Rather than putting you through a lot of computer science theory and trying to explain keywords and constructs and a lot of nonsense that I don't even know... I'm just going to drop it on you. You'll need to know a little HTML first, then we'll jump right into the javascript and all the fun stuff. We'll start simple and work our way up.
Now, open up notepad. First things first... Select File->Save As... from the menu bar. Change the "Save as Type:" to "All Files". This prevents notepad from adding ".txt" to the end of the filename. Name the file "index.html" (without the quotes) and save it to a place on your computer where you'll remember it (I usually save it on the desktop).
A long long time ago, someone decided that the default page of a website should be called "index.html". No one really knows why, but it's the standard. Sometimes, depending on where you host or what language you're programming in, the default name could be something like index.htm, index.php, default.html, default.aspx, or some other variation. You can name all the other pages of your site whatever you want, but the main landing page that the user first sees should always be one of those variations.
Enter the following code:
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
Balls!
</body>
</html>
Save the file. Open a new window in your browser (File->New->Window or Ctrl+N). Open the file you just created in the browser (File->Open->Browse).
Now, what you should see is a page with the word "Balls!" displayed in the top left-hand corner and the words "My First Webpage" in the title bar.
Congratulations. You've created your first webpage.
Now for an explanation of what this code means. HTML is a "markup language" which means that you're basically putting tags around bits of text. The tags tell the browser what a piece of text is supposed to do or what it's supposed to look like. Bits of HTML can be nested in other bits of HTML. For example, the "head" chunk is nested in the "html" tags and the "title" bit is nested in the "head" tags.
The <html> tags must begin and end the web page. This tells the browser that the page is, indeed, an HTML page and should be interpreted as such.
The <head> section defines meta-data (data about the data) relating to the page. This section is not rendered (displayed) in the actual page. It tells the browser, and some other programs, interesting information about your page. This is where we will later add in the Style Sheets and the javaScript.
The <title> tags tell the browser what should be displayed in the title bar. Makes sense, right? Because this is not information that is to be displayed in the browser window, it belongs in the header section.
The <body> tags define the content (or body) of the page. This is the section that will actually be rendered in the browser. Right now, we've only got a small bit of text (Balls!) in there, but later on, we'll be adding all kinds of fun things like tables and lists and images.
There you have it. A simple page that demonstrates the (very) basics of web programming. The vast majority of HTML tags are named according to what they do in plain English. The <head> tags hold header information. The <body> tags hold the body of your page. And so forth.
Keep in mind that HTML tags must be closed. When you open a block of code with an opening tag (<body>), you have to end that block with the matching end tag (</body>). End tags are almost exactly the same as the beginning tag, except the tag name begins with a forward slash (/). Also, keep in mind that all tags must be properly nested. When a tag is nested within another tag, the inner tag must be closed before the outer tag. For example:
<head>
<title>My First Webpage
</head>
</title>
The above bit of code is incorrect. The title tag must be closed before the head tag. Incorrectly nested tags may cause errors and your page may not render properly.
Another thing to make note of is that HTML (as well as most other programming languages) ignores most white-space characters. White-space is the space between words including spaces, tabs, and line-breaks. For example:
<html>
<head>
<title>My First
Webpage</title>
</head>
<body>
Balls!
</body>
</html>
<html>
<head>
<title>
My First Webpage
</title>
</head>
<body>
Balls!
</body>
</html>
The above two pieces code will render EXACTLY the same as your original code. The indention of the original example is simply there to make the code more readable by humans. Computers really don't care. Anything after the first space after a word is completely ignored. The only thing to be careful about is that a space at the beginning of a tag will break the code. Example:
<html>
< head>
< title>My First Webpage< / title>
</head>
<body>
Balls!
< / body>
</ html>
The above code WILL NOT work correctly.
There are ways to reposition elements and add extra spaces and line breaks, but we'll get to that next time. If you're feeling ambitious, you can google HTML and learn about other tags to play around with. If you're not feeling so ambitious, I'll explain new tags as I get to them.
--
Well, that's it for now. I know this hasn't been very exciting, but the information presented in this article has hopefully provided you with the very basics of web programming. Next time, I'll introduce javascript which, I promise, will be a bit more exciting.
Until next time,
~~Ben