Introduction to JavaScript Spring 2011 Class 3

esse quam videri
Jump to: navigation, search

Back to Introduction to JavaScript Spring 2011

Markup Review

Formula for (x)Html Markup

container tag:

 <element attribute="value>content</element>

examples:

Some really awesome text about some really awesome thing

 <a href="camelot.html">'tis a silly place</a>


empty tag:

 <element attribute="value" />

example:

 <img src="flyingSaucer.jpg" alt="a totally not-photoshped photo of a real flying saucer" />

Formula for CSS Style

 selector {
   property: value;
 }

examples:

 #navigation {
   background-color: #FF00FF;
   color: #00FF00;
 }
 #navigation ul.extra {
   float: right;
 }

Adding Javascript to Your Html

adding a script block

 <script type="text/javascript">
   document.write("this is not a good way to do this.");
 </script>

attaching an external script

 <script type="text/javascript" src="myJs.js"></script>

Which One Should I Use?

Script blocks put the javscript code right in your (x)html document. This was done a lot in the early days of Javascript, but is generally considered undesirable today because it interferes with separation of markup and behavior. I will allow use of script blocks in in-class-work for this class, since putting your Javascript in an external file is an extra step that is not really necessary for the quick and dirty in class projects. I expect your assignments and projects to be more polished, and will grade down for using script blocks instead of external code.

Where do I put my script tag(s)?

Some people like to put their script tags in the html <head> tag, usually chosen because it helps separate your javascript from your markup. The downside to this is that the browser interprets all of the javascript in the head tag before it loads the content of the page. In the effort of progressive enhancement, I prefer to put my script tag immediately before the </body> tag, so javascript is loaded and interpreted after the content is loaded.

A Bad Example of Hello World

 document.write("Hello World");

This is a bad example because it just writes the text in the markup wherever the script block happens to be, with out adding any markup tags around the text.

A Better Example of Hello World

 var helloWorld = document.createElement("p");
 helloWorld.textContent = "Hello World!";
 helloWorld.className = "fancyText";
 document.getElementById("paragraph").appendChild(helloWorld);

This example is better because it wraps up the text in a paragraph element (and even applies a CSS class to the paragraph), then inserts the element in a defined spot in the html, regardless of where the script tag is. Don't worry, this script is jumping way ahead, and I don't expect you to have a full understanding of it for a few weeks.

Basic Javascript Syntax

In that last example, the parts like createElement() and textContent are parts of the DOM. We use javascript to manipulate the DOM, and update our markup with out refreshing the page. Depending how you look at it, you might not consider those DOM methods and properties part of Javscript itself. So, before we start using DOM methods to manipulate the DOM of our webpages, we're going to learn the core parts of javascript using Firebug's console.

Variables

A variable is a reusable container for data. Most of our programming is taking existing data, whether it's data we already had, or data the user has entered, manipulating that data in some way, then displaying new data to the user. We store data in variables.

Declaration

To create, or declair a variable in Javascript, we use the keyword "var" and then make a name for the variable. We will use the name to refrence the variable and it's contents thought our script. It's useful to give your variable a name that helps you remember what data it's holding, but you can name a variable just about anything you want. The major restrictions is that they cannont be key words of the javascript language (like "function" or "switch"), and they cannot use some special characters (like '/' or ' " '), they cannot contain spaces, and they cannot start with a number.

I usually name my variables using camel case.

variable declaration examples:

 var thisIsMyVariable;
 var newVaraiable42;
 var superAwesomeExcitingVariable;

The space between the Javascript keyword "var" and your variable name is required. It's the only way Javascript can tell where the keyword ends and where your variable starts.

Assignment

After declaring a variable we can store data in it, known as assigning a value.

 thisIsMyVariable = "This is some text I want to save for later";
 newVariable42 = 2006;
 superAwesomeExcitingVariable = false;

The space on either side of the equals sign in assignment is optional. I usually use one because I think it makes the code easier to read, but the Javascript interpreter ignores it completely. You can leave out the spaces on either side of operators if you wish.

Once data is stored in your variable, using the variable name in your code will return that data. For now, we'll use the console.log() function to output text to the Firebug console;

 var thisIsMyVariable;
 thisIsMyVariable = "This is some text I want to save for later";
 console.log(thisIsMyVariable);
 >>> This is some text I want to save for later";
 var newVaraiable42;
 newVariable42 = 2006;
 console.log(newVaraiable42);
 >>> 2006

Sometimes you'll know the value you want to assign to your variable at the time that you declare the variable. In this case, it's possible to do the declaration and assignment in the same line.

 var thisIsMyVariable = "This is some text I want to save for later";

Data Types

There are different categories of data that can be stored in variables. The type of data determines what ways that data can be manipulated. For now, we're only going to worry about 3 types of data we can in a variable.

Strings

When we have a bunch of text, usually either text the user has entered into our program, or text we wish to output to the user, use the string data type, since the text is a "string" of characters. When we use strings in javascript, they needed to be surrounded with single or double quotes. If your string happens to have a single quote (or an apostrophe) in it, and you wrap the string in single quotes, the quote mark/apostrophe in your string will cause javascript to think the string as ended, and the rest will be unexpected characters, and the ending quote mark of your string will actually be treated as the beginning quote for a new string. If your string contains a single quote mark /apostrophe, you can wrap it in double quote marks, so the single quote / apostrophe won't prematurely close your string. Alternativly, you can use escape characters.

 var myString = "the apostrophe (') in this string won't close it because it's wrapped in double quotes";
 var myOtherString = 'the apostorphe (\') in this string wont\'t close it prematurely because I\'m using escape characters.';
Numbers

A lot of the data manipulation we'll do in javascript is math. We might want to change the width of a block level element, or move it's position on the page. We'll have to preform mathematical operations to do this. Mathematical operations can only be performed on variables holding the Number data type.

Boolean

When you are using variables to keep track of the state of something, that sate is often "on" or "off" with out any sort of in between. When we're keeping track of something that has a binary state like that, we can use the Boolean data type, which only allows two values, "true" or "false".

Operators

When working with a Number data type, you can do normal addition, subtraction, multiplication, and division using the "+", "-", "*", and "/" operators.

 console.log(1 + 1);
 >>> 2;
 
 console.log(1 - 1);
 >>> 0;
 
 var myFirstNum = 2;
 console.log(myFirstNum * 3);
 >>> 6;
 
 var mySecondNum = 3;
 console.log(12 / mySecondNum);
 >>> 4;

If you want to apply an operation to a variable, and then store the result of that operation in the same variable, you can do it like this:

 var myNumber = 12;
 myNumber = myNumber = 5;
 console.log(myNumber);
 >>> 15;

There is a shorthand way to do the same thing for addition and subtraction (sorry multiplication and division):

 var myNumber = 12;
 myNumber += 3;
 console.log(myNumber);
 >>> 15;

There is also a shorthand for adding '1', or subtracting '1' from a number.

 var myNumber = 36;
 myNumber++;

Notice I didn't put a space between the variable name, and the plus sign operator in that last example. Just like the equals sign operator, none of these operators need spaces around them. I put spaces in where I think they make it easier to read, but you do not have to do this if you don't want to.

Concatenation

Concatenation is the process of linking two or more things together in a chain. In Javascript (and most other programming languages) we can use an operator (the plus sign for javascript, different in other languages) to chain strings, numbers, and variables into one big string.

chaining two strings:

 console.log("This is my first string." + "This is my second.");
 >>> This is my first string.This is my second.

That'd look better with some more spaces -

 console.log("This is my first string." + "  " + "This is my second.");
 OR
 console.log("This is my first string.  " + "This is my second.");
 >>> This is my first string.  This is my second.
 userName = "Dave";
 console.log("I'm sorry " + userName + ", I can't do that.");
 >>>I'm sorry Dave, I can't do that.
 xPosition = 58;
 yPostion = 32;
 console.log("coordinates = " + xPosition + ", " + yPosition);

Conditional Statements

Often when programming, we want different things to happen based on a condition. Usually we'll check the value of a variable.

 password = "not4u"
 userInput = "please let me in"
 
 
 if (userInput == password){
 	console.log('password accepted');
 } else {
 	console.log('password rejected');
 }

a more complex example:

 var userInput = 36;
 if (userInput === 33) {
 	  console.log("yup, that's 33");
 }else if (userInput >= 34 && userInput < 36) {
 	  if (userInput == 35){
 		  console.log("No, that's 35");
 	  } else {
 		  console.log("oh wait, it's 34.")
 	  }
 } else {
 	  console.log("I don't know what that is")
 }