Web Development
Thursday, July 16, 2009
Professor: Good morning everyone. Any questions from yesterday? Anything all ALL? I posted new stuff on the blog about today’s lecture. Let me wait for another 2 minutes for the one person we’re waiting on. There’s some basic javascript documentations here on the screen.
Five more minutes and I’ll get started. Read as much as you can and we’ll start soon. We’ll get started. Anyone have questions about what you read so far or yesterday? Ok.
Student: I had nightmares.
Professor: You did?
Student: Wasn’t so bad.
Professor: Let’s run through what’s here.
[On screen.]
So the first part was how to put Javascript in a document. If you click that link there’s a description. There are three ways to put javascript in your document. First in the head of the document. This is an example of the head section of the document. There’s a script tag that allows you to put a javascript in the file. Same as the CSS file. The idea is that this links to the Javascript file.
Next way to do it is the exact same code on the inside of the body. Head and body – what’s the difference.
Student: Head is first
Professor: There is a good reason to put things in the head. The browser goes from top to bottom. Starts with head and goes down. If you want something to load immediately you put it in the head. You want those logics loaded before the visuals. There’s not much reason why you would link to an external link in the javascript file but if for some reason you need to do that you can. Some of the files I’ll show you I’ve done that. I’ll show those later.
The third way — put Javascript in the head, body or inside of another XHTML. Javascript can go as an attribute in HTML. There are special attributes — onclick is one. You can use this to call for a javascript function.
There’s also “onmouse over.” There are many attributes to trigger javascript. So what that does is that you can use scripts in the head or body to call javascript to open. So that was the document link from the blog. This is all there for you to read. I know that you can’t remember everything I say. It’s all documented. So you can go back as you need.
Ok. So the fundamental concept of javascript is the same as the concept of other languages. Javascript consists of logic and memory storage. The fundamental piece of memory that any program has is what’s called a variable. This blog linked from the latest post I just did explains a variable and how you would use it in Javascript. These concepts will apply to just about any program. People don’t consider HTML as a language but it’s a mark up language.
That’s what people talk about with programming. They talk about logic and conditional statements with different behaviors, etc.
Who has programming experience? Different brain types handle programming concepts differently. Some people get it right away. It doesn’t seem to have anything to do with prior experience. I think it’s related to logic. If you’ve done logic and math, it helps with programming but it’s not necessary.
I’ll go through it but feel free to stop me and ask questions as needed.
A variable is a piece of memory. That’s how to think about it. You’ll have to remember some of algebra. You have the same variable concepts. You have placeholders that are little bits of memory. A formula like y = 3 + 1 means Y equals 4.
So you can say Y has the number 4 in it. We stored the number 4 and put it into Y. That’s the concept of a variable. You’re creating memory and putting value into that. When I say what is the value of Y? You would say 4. You’ve remembered that Y is 4. That’s the concept of a variable.
So the computer knows that Y has the number 4 in it.
The letter Y is a variable. That’s what variable refers to. A variable is things that hold other values inside of them. It’s something that references some other value.
A variable doesn’t have to hold just numbers. Variables hold text, too. I could say Y equals “hello.” That stores the word “hello” in the variable. It can be numbers, text, some sort of objects, more sophisticated data, etc. The fact that the Y has storage capacity and store types of data makes it a variable.
I could say Y equals “hello” plus “name.” Anytime you see a word in JavaScript and most program languages, that’s not in quotes. You can see “hello” is in quotes and name is not in quotes. So something not in quotes is another variable. That’s a general rule. We’ll get into exceptions later.
So this equation means Y stores the word “hello” and glues it onto the other variable which is name. I’m using one variable to define another variable. So let’s say name has the word “bob” in it. So Y would be “hello,” space, “bob.”
Any questions?
If the name value was my name, this would be the direct equivalent of stating this. It’s as if name holds my name.
There’s a terminology difference between name and “[name deleted for privacy].” Name is a variable. “[name deleted for privacy]” is a literal. It’s not a placeholder; it’s the thing itself. “[name deleted for privacy]” doesn’t refer to another piece of data. “[name deleted for privacy]” IS the data.
So name is a placeholder. “[name deleted for privacy]” is a literal. Any questions?
In most programming languages, you refer to text literals as strings. That’s the word we use for text. “String” doesn’t mean a piece of string. “String” means text in quotes. So if I glue two strings together like the example on the screen, I end up with y = “Hello [name deleted for privacy].” That’s concatenating. So when I tell the computer to do “hello” + “[name deleted for privacy]” it’s the same as “Hello [name deleted for privacy].”
Any questions?
I have two variables in this example now. [On screen.] This is now JavaScript code that I’m writing. Var says I’m defining a variable. I’ll call that variable X. I want X to be equal to a number. So we want JavaScript to create a variable X and put a 3 in it. So think of X as a memory that stores the 3. So from now in the code X equals 3.
I’m setting variable Y to be equal to whatever’s in variable X plus 1. So X is a reference to number 3. The computer knows X equals 3. So now Y is equal to 3 + 1.
There are two separate things you do in JavaScript. You can declare a variable and define a variable. This is true in many languages but not all languages. You can declare to use a variable called firstname. I don’t have to define firstname right now but I can tell it to reserve that word for me as a variable. Before you define a variable, you have to declare your intention to use it.
We did that in the example earlier. We declared X as 3 and then we defined a variable. Whenever you see equal, that means you’re defining it. Declaring and defining are two slightly different concepts. So have to declare var X before you can say “= 3.” So after we declare it, we can define it.
On this example we’re declaring the variable. JavaScript is untyped. If you know programming and you know different text variables, some are numbers, strings, objects, etc., you get used to knowing a particular variable has particular properties. If I add two numbers, it’s mathematical. JavaScript knows all those standards.
I’m redefining a variable here. [On screen.] There’s declaring, which says I’ll use this variable. Defining is setting a variable equal to a value. In this example I’m declaring I and defining it as 100. I’m putting 100 into the letter I. So now I’m saying I equals I plus 1. I’ve added 1 to 100. I’ve taken the previous value and added 1. In the third line I’m overdoing it altogether and changing it to a string of text. I can always wipe something out and not keep the original value. The first line I set it at 100. The second line I change it to 101. The third line I change it to text. You can continually overwrite variables.
Once you define them, you don’t have to re-declare every time. You can continue to use the variable without re-declaring it.
Student: Is there a check? Or do you keep it in your head?
Professor: It’s up to you. I think that was a bad design idea. There are several languages that keep track of those things. But non-programmers originally found it easier to do this. But JavaScript is sophisticated so that increases the burden on the programmer.
In most languages, what we did up top causes difficulty. Most languages would force to use a number or a string. JavaScript is untyped. So you can continually overwrite data with other data.
That’s the introduction to variables. The variable is the placeholder that stores some value. You declare it with “var” and then define it by setting it equal to something.
Student: When you change the definition, how do we know when the first definition happens and then the second, etc.?
Professor: It sticks to it until you change it. I is equal to 100 until I change it somewhere down the code. Here it’s the next line down. You have to remember how you change it in the code as the programmer.
Student: So wherever it happens in the page is when the changes?
Professor: Yes. In HTML, it goes from up to bottom.
Student: Is that confusing to identify the variable?
Professor: There are some situations you want to change it. It wouldn’t make sense to do what I did in this example. But sometimes you’ll want to change the variable somewhere in your code. When you see it, it’ll make more sense.
Any other questions about variables? Let’s move onto functions, which is the second most important concept in programming.
Variables store memory of one particular type. A function stores a series of commands that get run as a whole together. You might remember in the variable explanation, I have two lines of code. [On screen.] These are two commands I’m instructing the JavaScript processor to run two separate commands.
A function is like taking these two commands and storing them in memory. We’re not storing a particular value but the idea that we want to run the two commands. Then a function tells it to run those two commands at some point in my code.
This isn’t a great example. Let me show something else. This is a function definition. [On screen.] This says I’m defining the function. Sorry, we’re declaring a function. It’s like when you declare a variable. So we give the function a name. So I’m using “showResult” as my name of the function. We’ll ignore (result) for now.
This is a set of two commands that I want to run at some other point in time. I’m declaring my intention to run these two commands at some point in the future. They only run when I call the function. I’ll tell the code to run the function at some point in my code and JavaScript runs the function.
So the function creates a variable message. “msg” is shorthand for message. It’s syntax. It says “the result of your calculation is” something. So then it pops up in a pop-up box. “Alert” is a built in function of the JavaScript engine that pops up a box. So this function pops up a box with this text message.
When I call this function in the code, I call it with an argument. The argument is in the parentheses (result). Let me go down the screen. [On screen.] This breaks it down line by line. Function showResult is a declaration. It takes one argument that I call (result). That’s a variable name. It’s going to take a variable called (result). I’m declaring my intention to use the function showResult.
Student: Are functions and variables case sensitive?
Professor: Yes, everything is case sensitive in JavaScript.
Student: So would you have “showResult” and a different function with “ShowResult”? Is it that specific?
Professor: Yes. This is a convention of using the first word with lower case and the second word capital case. It’s called camel case because it’s kind of bumpy. The “R” has a bump in the word. This is the convention I’d like you to use. If you have a word for a variable or function with two words, you can’t use spaces. So use camel case. So capitalize the letter of every word EXCEPT the first word. And all the rest of the letters should be lower case. We have a function called showResult. We indicated it’ll accept the variable that we call result. This next line — [On screen.] — here. That’s inside the function or inside the brackets. Inside the brackets are the commands for the line. That line is inside the brackets. It says “create a variable message equal to this text.” The result of the calculation is plus the result. What does that mean”plus Result.” It’ll glue together the “string literal” the literal value plus this word (variable). It’ll take the variable and glue it to the end of the text. What’s in the variable result? Depends on what we put in the function. This function accepts when you tell it to run it’ll ask for the value of the variable result. So you’ll tell it what to use for the value of the variable result. You can give it ten different values if you want. It’ll pop up 10 different messages because we add the result. We’ll go through that in a moment.
The last line inside the function is built in as a javascript function. This is “Calling.” This is how you call a function. You use the function name and in the parentheses you supply the value. This will accept a text then it pops up. So I tell it to call “function alert” and send this value of the variable. So it knows to pop up the text because I told it to. So is that clear? This is a concept that’s hard for people.
Student: The message. You can put an image or something else
Professor: Alert — this expects text. So it’s created only for text. There are other ways to pop up images
Student: It’ll have a message.
Professor: The variable name may be different. We picked this ourselves. You can stick other variables in there. The bracket closes the function. This is again, beginning (start of the lines of the command in the function). The ending bracket indicates closure.
I’ll go through everything again. Function is a declaration for a function. ShowResult is the same attached to the function. I use lower camel case which has a lower first letter for the first word and a capital letter for the rest of the words. You supply it when you call the function and this [On screen.] indicates the variable named message which depends on the value you supply. This pops up the variable message and is a built in function that exists in the browser. This is how you call a function. When you see a word in parentheses — that’s how you call a function and you recognize that as how to call a function. You won’t see the word directly followed by opening and closing protheses with something inside it creating nothing. You won’t see that and it not be a function. This will always be a function. That’s a declaration called a function.
So — this is another example of the same concept. I’m declaring a variable X. Setting it equal to 10. Declare a variable Y and setting that equal to X times 1000. So this is equal to 10,000. This multiples it and stores it in Y. Y is equal at this point to 10,000. Right? I’m calling that function showResult and passing it. This is called passing a variable or argument. I’m passing the argument 10,000. [On screen.]
So don’t mistake this for the variable. I’m passing the value of the variable. I’m saying call the function and send 10,000 not Y although they’re equivalent it can confuse you.
Student: Do you showResult X + Y?
Professor: You can do that too. I can also put in the number 10,000. So I call the function and send the number 10,000. When the function gets called in the code you see the word with the protheses. So you know that’s a command to run the function. It goes to where we define it to run and it tries to run. It puts 10,000 in automatically. When I supplied the number in parenthesises. So that’s why I try to drill in the point that this doesn’t send Y it sends the value of Y (10,000). So we call a function and supply it with the number 10,000. The function the way it works, it knows to expect to receive a value. It doesn’t know the value but it knows to expect it. Then it puts the value in “Result.” This indicates the name of the function as well as the fact that it expects to receive. When it’s called it puts the value in “Result.” Then the result is 10,000. Then that pops it in the window.
That’s the 4 concept of function definitions. Whereas the last function had one argument I’m now showing there can be many variables. This function according to this declaration would expect 2 values not one. The two values are put in two variables – parameter 1 and 2. It’s up to you as the coder to determine your functions. So you can call it this [On screen.] — you determine the function and it gets passed to these two variables inside the function.
Who’s confused?
Ok. Anything specific? We’ll see this in action
Student: The result … how did the result know …. I understand showResult. Is that the result? I get it but ….
Professor: This?
Student: Just … showResult Y. Ok that’s 10,000. I get that. But the result in parentheses … ????
Professor: You start here [On screen.]? So you understand Y is 10,000. So we call the function and tell it to take the number and do something. Like a factory. That’s the function. So we take the raw material of 10,000. The number that you give the function gets put automatically in the variable call result. The result in this case is 10,000
Student: How does result — if there’s more than one math function??
Professor: When I call it. Good question. When I declare the function it’s not run right away. It’s not processed right away it’s stored in memory. So I can run that a hundred time. I can run the same function as many times as I want. When I call it I tell it the value. So I can say “run 10,000 in the variable result.” Another time I can say “run 5.” What you put in the parentheses is what is put in the variable result.
Student: ShowResult is result in a way?
Professor: ShowResult is the function name.
Student: I don’t have a question.
Professor: General anxiety? I’ll help you through that. [Class laughing.]
When I show these in practice it’ll make more sense
Student: Can you show it using the example you gave in the first description of javascript. The head of the HTML there’s a box … Is that possible?
Professor: I’m not sure what you’re talking about.
Student: The first page of javascript. One of those examples. …. the one you just passed. Can you click on one of those. Is it too far fetched?
Professor: Ok. When I call that function alert that’s what pops up. This technical looking box. If you want to look at the javascript code you can “view Source.” This will bring up the code. We can look at this. So this shows a regular HTML document. Down here [On screen.] at the end of the body is this script tag linking to an external script. The script does something. The code is not here. The code is in the external file or else you’d see the code here. There’s no code, just the link. So if I want to view the code you view the file here. [On screen.]
Yes. I want to show how to do the browser by itself first. So if I want to look at the file in the browser I copy the link. This link is relative to where the HTML document lives. So I copy and close the window. And so relative to the HTML document I can take the name of the document and paste the script. It’s in a subfolder called scripts. It has only one line of code.
This is a command calling the function. You see the word. And it gives a “string literal” hello world. Every string has a semi colon. It supplies it with one parameter “hello world” the engine knows to pop up the window with the X. If I said “hello morning” it would pop up that. It depends on what you supply as a value.
So does that explain it?
Student: I guess with time.
Professor: I’ll go through more examples. So let’s go through the example listed from the blog.
We’ve seen how to link the different ways in javascript. Head, body or HTML. I’ll skip the top section. We’ll see that anyway as we demonstrate. These are there to show you the concepts.
So here’s an example of creating a variable and printing the value of the variable to a page.
[On screen.]
So this created a variable and this is the result of the variable of the javascript function column. View page source. You see there what the javascript looks like. It’s not the best format in HTML. My tabs are funny. But the idea is here’s the beginning of javascript. This is a script tag that indicates Javascript code This is the end tag. So between the opening and end is javascript code so it’s known this is Javascript not HTML. Within the script tag I have two lines of Javascript code.
The first one creates a variable. It declares the variable msg. It puts “hello world” into it. Document.write is a built-in function of the browser. It writes whatever’s in the parentheses as the argument for the object. So it’ll write msg, which is “Hello World!” So that’s why you see that text on the page. Any questions?
Let’s go to popping up a variable in an alert box. This is what we just saw with a different code. So you load the page and an alert box pops up. This is similar to what we just saw. But instead of document.write, we use alert. It pops the message up in a box. So I’ll view the page source.
This code is almost identical to the last example but I’m using alert instead of document.write. So we have the beginning of the script tag and the end of the script tag. The two lines are in between those so the browser knows it’s JavaScript and not HTML.
We put the words “hello World” into the variable of msg. And then we define the alert as msg. And then it pops that msg into a box.
I’m going to show you pitfalls of JavaScript as an untyped language. These are different ways to add things together. [On screen.] In some cases, 10 plus 20 is 30. In other cases, 10 plus 20 is 1020. Other cases, 10 plus something is 10something. And then sometimes 10 times something is NaN, which is not a number.
The fact that it’s untyped is somewhat misleading. So the 10 plus 20 on the first line, these are number integer literals. They’re not variables. They’re literal values. What we see is what we mean. We’re not referencing something else. So JavaScript takes the numbers and puts them together in a mathematical equation.
When you put quotes around the numbers, JavaScript converts them into strings (text). So behind the scenes, there is a difference when you put quotes around the numbers. They’re treated just like letters. So that means you’re gluing the strings together. So the result is the glued together form. So it’s 1020. Be careful when you’re using numbers and strings. Try to make sure your numbers are outside of quotes and strings are inside of quotes.
In JavaScript you can add a normal number to a string. So that converts the number to a string automatically. So it’s attach the two pieces together as if they were both text.
Student: So if you had R2D2 plus 2, it would be R2D24?
Professor: No it’s R2D22. The third example it’s adding 10 to a string.
The fourth example is trying to convert the word to a number. So you end up with an error saying that the value is not a number. Something went wrong. It doesn’t know what to do in the fourth example. JavaScript tries to figure out what you’re talking about, but in the fourth example it doesn’t get it. When you see NaN, JavaScript doesn’t know if you’re dealing with texts or numbers.
That’s the problem with untyped languages. Let’s move onto the next example which is exhibiting the differences between adding and concatenating strings. JavaScript uses the plus sign to indicate concatenating. So “Bob” + “cat” = “bobcat.”
This is actually the exact same thing so I won’t go through it.
Let’s define an array. Let’s view the code here. An array is a list of items. A variable is a single item. An array is a type of variable that’s a list of different elements. An array can hold an infinite number of subvariables. So here we declare an array. [On screen.] It’s exactly like any variable declaration. I call my variables that hold arrays arr plus some word. That way I know it’s supposed to be an array. I call this built in function a new Array. It’s not just a single variable. It’s a list of values.
On the second line, I’m defining the first element of the list to be “item 1.” The second element is “item 2,” etc. So arrItems has a list of other subvariables. It references four different variables. It starts with zero, then 1, etc. So when I want the first list, I’ll ask for arrItems0. The indexing starts with 0. The first value is always zero.
Can everyone read that? [On screen.] I wanted to minimize it so there’s no text wrapping.
So here we have a loop. [On screen.] This is sophisticated. We’re looping through the array. That means we’ll keep trying to find new values stored in the array until there are no more values. Then we’ll print them out on the page one by one. So it starts with index equal to zero. So we’ll start with arrItems0. We’ll keep going until the number we have “i,” is no longer left in the list. We’ll increment that number by 1 every time we try it. This is a repeated task we run called a loop.
It assumes i is equal to zero. It adds 1 each time we do the operation. It continues until there are no more elements in the array. This is getting more complicated. Each time we run this command, this is what it does. [On screen.] It will create a variable called “line.” It sets line equal to an HTML p tag. It’s concatenated with an array and then concatenated with the ending p tag.
I’ll run through that process one more time. We have an array at the top. We create the list of things which is the array. We add four elements to the array stored at indexes zero through 3. So if I want the fourth element, I have to look for 3. 3 has item 4. 2 has item 3, etc. Does this make sense?
Each element in the list has a number associated with it. Down here, [On screen.] We will go in a loop and repeat a task over and over again. How many times we repeat the task depends on the number of elements in the array. We’ll start from the zero index of the array. We’ll continue one by one until i is equal to the number of elements in the array. For each element, we’ll print it out.
I’ll show how that works. So we’ve printed out the contents of the array for each element. We started out with the zero element, then the first, second, and third element. We’ve looped through the elements of the array.
I didn’t have four document.write commands. I just have one but it printed out four things. I’m only telling it to write once, but it prints out four things. This command tells it to loop through the code multiple times. I don’t want to get bogged down in this right now. But this is a way to creating a list and then telling what to do with the list.
Student: I’m confused. You have to have the top part with all the list numbers. So how is that faster?
Professor: Eventually we won’t write it out each time. We’ll eventually have it more automated. There’s another way to do the top part. This is very conceptual. I’m just going through the concepts. I want to get the point in that the array is a list of things. You can iterate through the array one by one.
Student: Is i always the value for the list of the array?
Professor: I haven’t gone into that so much. This bottom code is what’s called a four loop. There are three arguments or subsections to this line. There’s the starting part. When this loop first runs, we create a variable called i. We can name it whatever we want. We’re creating the variable var i.
Student: Did we define i?
Professor: No. I should technically have declared that I was going to use the variable i. So imagine that I did that. We’re declaring i and setting it equal to the initial statement. So it starts with i and then do the two lines of code. Since i equals zero, it decatonates and then writes back to the page. Next time around, i equals i plus 1. So it creates another version of i and then adds 1 to it. I’ll get into it more later.
So let’s leave that for now.
Let’s run through some concepts we’ve talked about earlier. Defining and calling a simple function, we’ve seen how that works conceptually. Here we have the same idea. [On screen.] We’re calling the function which is popping up an alert box. We can click to view the contains of the file. We’ve already seen this same code. It’s a function. It’s called showSomething. This one does not take any parameters. It’s not expecting you to supply it with data. It creates a message and pops up the message in an alert box by calling the built-in alert function.
Any questions? We’ve seen this code on the blog before. We’re creating a function, defining the variable, and popping it into an alert box.
Now we’ll move to passing an argument. This is the same code as the prior example except this function expects to be supplied with a parameter. So you tell it what to pop up in the alert box. The function just alerts what you supply it with. Whatever you call and give the function is what pops up in the message. It’s not hard coded in the function.
I’ll view the source of the HTML page. You’ll see the JavaScript code. [On screen.] Everything highlighted is JavaScript code. Here is a comment. It’s not evaluated as being actual JavaScript code. It’s just a note for you.
Student: How does it know where it ends?
Professor: This is a one-line comment. The // indicates that everything on the one line is the comment. The next line is not part of the comment. The two lines here should all be on one line. If you have a line break, there’ll be an error. I just had to adjust the screen for viewing.
This is a line with a variable called msg. Then we have a function that gives it text to do something with it. We call the function and then we pass the argument as text to pop in the alert box. The control in this example is slightly different from the last example. Prior, we just ran the function and it popped an alert box with hard coded text.
In this example, we define the text and then we call the function and supply it with the text. So you could change the contents of the alert box. In the last example, you changed the function itself.
Questions?
Let’s move onto the next example.
Here we have if else statements. Here we get into logic. If something then something. So if you view source on this file … the logic part of is the script. So this is creating a variable i Which is created and set to 10. This checks if i Equals 10. If i Equals ten it’ll run the code between the brackets. It’ll show us that. Otherwise that’s what “else” stands for if that didn’t work then it’s not 10 and will run what’s here in these brackets “i Equals 9.” If it’s equal to 9 it writes this text. If neither is true it’s write out “is not equal to 10 or 9.” This is simple “if, else” statement. If one thing is true do this code, if that’s not true then make this other code, etc. You can have many else, if’s. You don’t have to have just one else/if. I can make conditions for a variety of code. This is a conditional statement. You check to see if a condition is true or false. Is i =10. Yes or no? Am I the instructor? Yes/no. The way to think about it is matching condition. Is this correct? In this case it IS correct. So it’ll skip the other two sections. This is the nature of if, then. It skips what’s not true. If we change this to 9 it’ll skip the false statement “i.=10.” It’ll try to match. So I’ll modify it now. [On screen.]
So now I’ve changed it to 9. Now i = 9. So it’ll only run the code that matches that condition. So let’s make sure that’s true. This should say i = 9. Not the most exciting example. But it shows that you can match conditions. We’ll use this extensively — this concept of else/if. So questions about “if”? Let’s run through that again.
Student: Why do you use a double = sign?
Professor: Good question. If I said i = 10 it would take 10 and put it into i As a variable. So many C based languages use double equal signs for comparative commands. Comparison compares the two to see if they’re equal. That’s the double equal sign. It compares the value of i To 10. Are they the same? True or false is the comparison. The code values if the variable is true or false.
Back to loops. Next example …
Loops are critical to code.
So let’s view page source. This HTML document has all the regular HTML stuff. But includes Javascript. This is an external script because it includes the source and external file so you know you need to look in the file. This is like CSS. However we have the script tag here that doesn’t have the source attribute. [On screen.] this does, this doesn’t. Between the opening and closing tag you’ll see the script here on the page.
This you should recognize as a function call. This function is loop. You see the word and the function next to it.
We’ll look in the script file and see where the function is declared. It’s not in here [On screen.]
Copy that. Paste it up in the top. Ok. So here I’ve done what I didn’t do before. I use the variable called i What this function does — this is the name of the function. Between these two brackets are the commands run when you call the function. When you call the function it creates the variable i Then you repeat the task. When you see the word “for” it means you’ll be looping. It could be one line or multiple lines. The nature of the for statement is that it has 3 conditions it uses to decide how many times to run the task. This will be run several times depending on the conditions. For takes the starting point. It’s common to see “setting up a variable = something Else.” This is putting 1 in the variable i The first time you run the loop it does something with the number. This case it’s writing out the number with a break tag. We write the number like HTML. The second time around i ++ get’s evaluated.
What this means is i Is equal to i + 1. This means that i = 2. It takes the value of i And adds 1. Each time it runs it increments the number we set in the first condition, in this case the number 1.
After it increments that number before it runs the second time it checks to see if the condition is 2. Is i = 2. The first time the loop runs i = 1. So it writes the number 1. Then i Becomes 2 and gets incremented. The code checks that i Is less than 10. Then it increments and checks to see that 3 is less than 10. Then increments 4, checks to make sure that 4 is less than 10, etc. Until i =10. This checks to make sure that 10 is less than 10 which isn’t true so it won’t write the code anymore.
So that’s the nature of a loop. You have a condition that has to be true. It’ll quit after this is no longer true.
Student: That function writes it out. So you don’t have an argument. Is that why the top bracket is empty?
Professor: This is the receiving end of the function. So that’s not really related to the output. Think of a function like an assembly line. It takes in one thing and spits out another.
Student: If you took out the middle would it go to infinity?
Professor: This for loop. The statement “for” has to have 3 things inside it. But I’ll show you what I can do.
[On screen.]
You can just use “true” so this is always true and always keeps going. If I say false it’ll never run or process. So if you want — let’s try it. It’s infinite loop. It’ll crash the browser. Unless the browser is smart enough. These browsers can detect … See how it’s loading? It’ll eventually detect it. I hope
[Class laughing.]
Now we can’t do anything. The browser is crashed.
That’s the nature of for loop. You have to be careful so you don’t put yourself in this situation
Student: This is similar to Java.
Professor: Yes. All C based languages are the same. Javascript and Java are both C. They’re like siblings. They’re not designed to be like ..
Student: If you know Java you can apply it to javascript?
Professor: Sure. Definitely. Or you can apply it to C or C sharp or Python
Student: They’re all based the same?
Professor: Sure. I think they’re common. They use functions and variables. So everything applies. An untyped language — Java is not an untyped languages. So there are differences. We crashed the browser here. So I have to quit.
So just to review … “For” is a command for a loop. It starts with one condition. It runs what’s in the brackets and increments — in this case 1 – and stops when the condition is no longer true.
So another loop is called a “while loop.” This is a slightly different loop. Same is true to make sure if something is true or false. The While loop looks like this [On screen.]
That’s the HTML file. Set up the same as the other file. We call it function. The function is defined in the external script. We look in the script to see the function.
This is a while loop. Unlike the for loop, which takes three conditions, the while loop takes one. So long as this condition is true, it keeps running. So we start out with variable i as 1. As long as i is less than 10, we run these two commands. We write out some text. We increment i by 1. It’s very similar but I’m incrementing in all line down here.
We’re setting up i as 1 initially. We’re incrementing each time we run the loop. We run it as long as i is less than 10. This is the same as the other loop. This is just another way of doing it. We’ll go into why it might be quicker to do one versus the other at a later point.
The output is exactly the same as the last one. It quits when it hits 9 because 9 + 1 is 10. 10 is not less than 10, so it doesn’t print out. Any questions?
Student: Why not use that one?
Professor: Let me think of an example. I can’t think of anything to prefer one over the other right now. When we get into database queries, etc., we’ll see the conventions people use for the codes is one over the other. Conceptually it’s not too different.
Less than or equal to is a good question. You don’t have to just have a less than sign. You can have less than or equal to, greater than, greater than or equal to. You can also have not equal to. != is the not equal to sign. Double equals is the comparison. Not equals is !=. Greater than is >. Less than is < . Greater than or equal to is >=. Less than or equal to is <=.
Now we have foreach loops. Foreach loops are most useful in an array situation.
Remember I said you have an array indexed by number. Sometimes your arrays are indexed by words instead of numbers. You can index an array with numbers or words (strings). In this case, the element of our array called arrItems ["something."] When I say the code is equal to nothing, it matches it up with “item 2.” Sometimes you forget the names you give things. Sometimes it’s not important what the index is. You just want to loop through the items in an array. This is how you do that. It doesn’t matter whether you use numbers or strings. It goes through all the elements in the array and prints it out.
For is another for loop. It’s a variation on the for loop. It says for each item in this list of items, for each element of the array, print out something or do something. It goes through the elements of the array and puts each element in a variable called item. Item is a variable name. It’s receiving the currently iterated element of the array. Then we’ll create a line of text and printing it out based on the item.
Foreach loops are identical to while loops or maybe for loops but there are reasons why you would use one over the other. I’ll go into that later when I show examples. This is another way of looping an array. Any questions?
Let’s continue. The foreach loop is the least frequently used loop with the stuff we do in this class.
Now we get to fun stuff. What do you actually use all of this for? This isn’t real-world but we’ll show that you can detect different user events with JavaScript. When I click this button, the pop up comes with the alert. So instead of waiting for the page to load, you can wait for the user to do something. We can view the source. [On screen.]
There’s an input tag. Remember, the type button is relatively useless on its own. It doesn’t have a default behavior. That’s good for us because now we can attach JavaScript event handler to it that does something without worry about what the button would normally do on its own. So we add this to the input tag. [On screen.] It’s a special attribute. The browser knows we’ll indicate a behavior when something happens. So the browser knows what to do with this code.
The browser runs the JavaScript code. In this case what am I doing? The word is in camel case. What is this code doing?
Student: Calling a function.
Professor: Right. It’s a word with parentheses so it’s calling a function. Whenever you wonder what that function does, I usually define functions in an external script. In this case, it’s an attribute of an HTML element. But the function is pure JavaScript so it can have its own file out of the way. My function is defined in that file. I’ll copy that file into the browser so we can view it.
[On screen.] That’s what the function does. It creates a variable called message and puts the word “Hello” in it. It pops that in an alert box by calling the built-in JavaScript alert function. Now this happens when the user clicks a button. If you look at the HTML, this function is attached to the button. It’s in the onclick attribute. When you see onclick or onmouseover, you define it as an HTML element that you want to apply to that behavior.
Any questions?
Student: The onclick can be on any element?
Professor: Any element that displays on a page. Let’s do onmouseover. This is very similar. Instead of responding to a click, it responds to mouse over. So when I move the mouse over, something happens. It responds to a mouse over even though it says “click me.” That’s bad interfacing.
Let’s open up the script. Just like the onclick attribute, we also have the onmouseover attribute. The browser interprets it as JavaScript code. That’s straightforward. When someone mouses over the element, it says “Hello.” So that’s identical to the last example. Let’s take a look at the code.
It’s the same function. [On screen.] Questions about any of this so far?
Student: Is all of the “say hello, etc.” a nature of the JavaScript? It seems like a weird way to write it all out. When you call that out there’s mouseover, quotations, say hello, brackets, quotation marks, etc.
Professor: The reason for that is XHTML attributes are all in the same format. The value equals some other value in parentheses. So this has to be equal to something in parentheses. That’s how XHTML is defined.
This is a JavaScript command I’m running. It can only be followed by a semicolon. If you didn’t have that semicolon, it’ll still function. But I want you to get into the habit of always putting the semicolon at the end. You’ll thank me for it later on. When you have a series of commands, you’ll need that semicolon.
That’s how you attach behavior for onmouseover. Let’s take a look at another. They’re all very similar.
This is detecting mouseout. So when the mouse over happens when I mouse over, in this case I mouse out and it triggers. It’s almost identical to the first two examples. In this case, it happens with the onmouseout attribute. You see how it says onmouseout. Now it says goodbye. SayGoodbye alerts another function. If you wanted to look at that function, you can go to the XHTML script that’s defining it.
Let’s take a look at the next one. You can detect that the page is loaded. This function waits until the page is fully loaded and then pops up an alert. That happens with this code. [On screen.] The body actually has a special attribute onload that waits until the page is loaded and then does the function. This is how you code a function to wait until the page is loaded. That can be important sometimes.
Any questions? That’s not a user interaction issue.
Student: What if the page continues loading?
Professor: Did that example do that? It finished loading for me. Try refreshing your browser.
Student: If you click on ok it stops loading.
Professor: When that alert is open? That’s a good point about alert boxes. I use them just for debugging and testing code. You usually don’t want that popping up. You’ll find other ways to display information to your user. I use the alert pages to debug so that it halts programs in the middle until you figure out what you need to do next. It’s a useful feature that it stops the function until you click on it.
Student: The page fully loads
Professor: It’s the same effect as if you had it on the bottom of the body. Let’s go to the next example.
Let’s detect that someone has submitted a form. You enter text and submit. There’s an alert message. There’s a special attribute that detects if someone has submitted a form. That looks like this. [On screen.] It’s onsubmit attribute of a form. We’re saying here’s a form. There’s stuff in the form. When a user clicks submit, do some JavaScript code. It’s the same context except this goes in the form first. There are specific tags that accept specific attributes.
The form tag has a special onsubmit. The function I call when the user clicks submit.
Student: Does it always clear the form?
Professor: So you click submit and it went away? That’s because you submitted data. So this submits the data and reloads the page. There’s a way we can prevent the form from doing that. We’ll get into that later.
Now we get to the more fun stuff. These are basics. I’ve shown you how to structure JavaScript code and write it, where does it go in the HTML code, etc. I’ve shown you how to wait until the user does something before triggering JavaScript code. Now we’ll combine it and change the behavior of the page.
This is called dynamic HTML or AJAX, though AJAX is not correct technically. We’ll use onmouseover to change events. So there’s a bunny changing to a cat. This is swapping two images. One image starts until the user mouses over and then the image changes. They both have individually addressable events. I mouse over the image and it knows what to replace it. The same thing with the second image.
Let’s see what the code looks like. This is image swapping. We’re waiting until the user does something and then the image gets loaded.
Let’s focus on the image tag. So this is an image tag. You’ve seen these before. You’ve coded them. You’ve given it an ID as image 1. This is reference, not code. So this is for style for this image. Same with javascript. When I mouse over the image it knows to look for that image with that ID not another image. So we reference one image not another. This is the source file for the rabbit. When the page loads it shows up (rabbit image). When the usermouse is over, we call a function with two parameters. Between the parentheses is the function. The first is the ID, the second is the file name. Understand? It’s like the functions we called before but we have two parameters. The first is the ID and the second is the file name
Student: Double quotes matter?
Professor: You can’t use double quotes on the inside. Because they would think it was the beginning and end of the HTML object. So we have to use single quotes internally. Double on the outside. So I can mix and match as long as you’re consistent which is on the outside and which are on the inside. So now we look at the swap image function. The most important part is calling the function the right information. The ID (image 1) and the file name we want in place of the image tag. Let’s open the Javascript file and see the function. So ignore this for now.
[On screen.]
So swap image is a function. It takes two parameters. You know that right? It stores them and puts in two variables. One LID and one for new image. These are variable names I’ve chosen in my code. Now we access the HTML element itself. We get an element by ID so it stores it in it’s memory in imageEL. [On screen.] The element we get is the element we assigned by the ID. It takes this ID and gets the element data and stores it in a variable image EL. So there’s an HTML for what an element is. This is not a number or string it’s an internal object representation. So don’t worry about what that is but remember this is a built in function to get an object by it’s ID.
Here we change the source attribute of the image tag. So that element has a source attribute. We’re changing that to the new source of the function.
So let me repeat what this code does. When you mouse over the image it triggers the “Onmouseover.” We defined in the XHTML code for the mouse over image (ID.1) we call a function “swap image.” We have the ID of the image we moused over. The second is the file name we want to load to the image space. We change the source file of the image to this file here. This happens in the function because it expects the ID and the new image path. It gets the image tag in an object representation. It gets data from the image and stores it in image EL and changes the source property to be the new URL for this function.
Questions about this function?
You can see that actually there’s only two lines of code in the function and only one bit of code in the HTML. It’s simple. You just change the source property of the image. You see when I mouse out it does the same thing except it’s switched back. It’s the same function getting called. When I mouse out it triggers the mouse out and it gives an image ID of the image we moused over but the original file to put back in the spot. So the rabbit is back where it was before. It reverts back to the original image.
So it does the same thing for the second image except it’s a different image ID. The image tag is the same but the image ID is the ID of the second, not the first. That’s how the code knows to change the second image.
Questions about this example? You’ve seen this before probably. Student: Let me ask a question. Maybe it’s … from the user experience how is it different from sprite [sp?]
Professor: This looks the same. If I mouse over I can change it to a different icon. There’s no real answer. It’s the same experience. If you have a sprite you have two images on top of one another. This would be done the same way in Sprite [sp?] You can do it one way or another it doesn’t matter. Sprite is used for smaller icons. It’s more work for the server. So it’s used for small files to save the server. You don’t see it used so much for this big stuff.
Ok. Now to the next example. Modifying an individual style sheet. Here’s the basic HTML. When I mouse over the font changes. Mouse out it changes. This is not so different than the code we just saw. Let’s go to that code. [On screen.]
Ok. So we have an external script linked from the head. This is the same for all the scripts. We have this one paragraph with an ID of P1. It has two functions one for mousing in and one for out. So when you mouse over the image you know already that this is a function. You see the word with parentheses next to it. So you recognize that as a function. So we call a function called “change font size.” We have the ID of the paragraph we want to change and the point size we want to change it to. When you mouse out you change it to the default on the browser. So this is like the image swap right? Same set up in HTML. You mouse over there’s an attribute and it supplies an ID and the data you want to use.
So let’s open up Javascript file. The first line is the same as the image swap. Just the function set up is that you have a declaration, name in lower camel case, the parameter of the ID, and the second parameter is the point size. So first what it does is take the ID in parameter and gets the corresponding HTML element and stores it in memory. You get the element by the ID and store it in the variable EL. In this case instead of changing the image source we change the style sheet font size property. This references the CSS saying “get the style corresponding to the element and get the font size and change it to the new size of the function ” You see there’s a notation. There’s an element, property, and sub- property.
This is an element that has a style associated with it called font size. This is a hierarchy. The element has a style and the style has a font size.
So when you pass the parameter is what the element will get. When you mouse over it changes font size and mouse out to change to original. Mouse over is 20 point and mouse out is 12 point.
So far so good? Questions?
This is a technique we’ll see over and over again. You’ll always have these handlers that will trigger javascript. Mouse over, out, these are events the user does to trigger javascript functions. Most likely you’ll have an ID for the function which gets the element by an ID and changes the property of the element.
Student: Can you do that again?
Professor: The first line is like a CSS selector. You have an ID and it finds the corresponding element. The javascript scans the elements to find the ID. It takes the paragraph tag and stores it in memory. EL — Has a built in property called style that has a built in function called font size.
You say “font size 10 point” [On screen.] That’s how you do it in CSS. It happens that in javascript you have the same words but in lower camel case. You can’t have a dash because that would equate to a minus mathematically. So it references the style sheet font size and changes it to the new size. That’s ok?
Student: The top is the new size?
Professor: No. It goes top to bottom. This is like a final end result. It takes the new size and changes the font size on the screen. This is the last line, nothing happens here. This is a permanent change of the font size.
As soon as the line is run “font size = new size” it shows up on the page immediately.
So let’s move onto another example. What we saw is an example of changing ONE single property of an element, the font size. Often you’ll want to change multiple properties. For example you may want to change the border, color, etc. When you work with CSS how do you change the attributes of elements?
Student: Class
Professor: Right. So if you want to do a broad change you would give it a bunch of properties. So same with Javascript. If you want to make a lot of changes change the class name as in CSS.
In this case, I’m trying to show you can change a variety of properties. This isn’t a pretty example. But you can change more than one thing. We change the background color, the border, and the width all at the same time. Let’s look at that code.
[On screen.] It doesn’t have much difference between this one and the last example. The difference is that it has an ID and also a class associated with it. ID is p1. Class is class1. Let’s open up the style sheet.
I have predefined in this style sheet two classes. I only have one element on the page. Class1 is blue. Class2 is green. There are some differences. It’s regular CSS classes. When I mouse over, I’m calling a function the applyClass which is defined. I’m supplying the ID I want to change and the class name I use for it.
By default, when the page loads, it has class 1. When I mouse over, it changes to class 2. So it dynamically changes the class that I’m using for this element. When I mouse out, it dynamically changes back.
Let’s look at the JavaScript. [On screen.] It’s very similar to the other two examples. It’s a function that takes two parameters. It has an ID and a class name. It takes the ID and the element that has that ID in memory. It uses the variable el. It changes the class name of that element to the new class name.
When I call the function, I give it p1 and class2 as parameters. It code scans through for p1 and puts that in the variable el. Then I change the class name property of el and changes the word to class2. Think of it as modifying your el code. When that happens, it’ll change the style because the style sheet indicates this style for class2. So as soon as I change the class name, the style changes automatically.
Then I can change what class1 and class2 look like. I can keep my code in my CSS file. That’s more initiative. If I change the look, I don’t change the JavaScript code but the style folder which is where it belongs in CSS. Your JavaScript is more burdensome.
Any questions? You can see there’s a trend to how we approach these things. They’re structured the same way.
Now we’ll do one final example. We’ll make something appear and disappear. By default, this paragraph appears on the page. When I click the button, it disappears. We’re changing the style sheet properties. We make it visible or invisible by clicking a button and calling a function to change the style sheet. Let’s look at that code.
[On screen.] I have an external script file with functions defined in it. There are two buttons for “show” and “hide.” Button #1, when you click it, calls a function called showElement. The hide button calls a function called hideElement which takes the parameter of the element to hide. Let’s look at the JavaScript because it’s interesting.
[On screen.] Here is showElement. It took one parameter which is the ID of the element to show. It gets the element but its ID. It scans through the XHTML code until it finds the appropriate ID. It puts that into memory in a variable called el so we can do something with it later. We’re changing the el style property and the sub-property display to be blocked.
There are two kinds of display. Block has things before and after in a rectangular shape. Inline flows across the page with no line breaks.
In this case, we show this as block. That makes it visible.
HideElement is the same. The display property is set for “none.” That makes it invisible. There’s block, inline, and none which are three display values. What people usually do is use block and none as the element for showing and hiding.
When I click the hide button or show button, it will look through the code, find the ID p1 and change the property of the block. When I click hide, it calls the function, scans the page for ID p1 and changes the property to none. So it disappears entirely.
There’s one difference between this and the other techniques that you should note. When I click the button, the ID I send is not the button itself like in the other examples. In this case, I’m sending the ID of an entirely different element. JavaScript doesn’t care which element I send. It’s a useful technique for one control affecting the other control, which is a paragraph in this case.
You can think of the function as being impartial. The function doesn’t know what was triggered. It just acts on the ID behavior of the parameters.
That’s all of the examples I want to show for JavaScript today. Any questions about any of this? On a scale of 1 to 10, how difficult is this? Greater than 5, raise your hand. Less than 5 is good. Less than 3? Is it less than 3?
Student: People are too embarrassed to raise their hands.
Student: I’m amazed. I’ve been doing this for 10 years. To get all of this in one day, I would be overwhelmed. Different syntax and HTML syntax, CSS syntax, JavaScript syntax, plus functions and for loops, I’d be overwhelmed if I didn’t already know this.
Professor: The two-week course is crazy to begin with. But I think students sometimes do better in a short class than a longer one because it’s more intense.
Student: It’s one thing to hear you talking and then reproduce it yourself.
Professor: That’s a flaw of the short classes. You don’t have a lot of opportunity to produce things yourselves. But we’ll do that for the next half of today. Every topic in a long class has a full week.
Take a 10-minute break. We’ll come back at 11:40.
[Break.]
We’ll get started again. So I pulled up another example on the screen here. It’s NOT posted to the blog. But if you go to my summer/2009/class4/form_values you can see it. I’ll post it later. I just wanted to use it as an example for now.
So I published a new post for this link in that folder. So click that to see the list of examples of detecting form elements using javascript. So the first ones are the text input.html. So this is an input field with a username and password. We’ll type something in.
[On screen.]
Doesn’t matter what you enter. Click “Login.” You’ll see a pop up box that says the ussername and password. By looking at this you see that when you click the login button it calls up a javascript function. So you see this on the web and understand that it’s a javascript function for alerts. So you have access to the code. So pull it up. You’ll see … that there is a script file linked in the head. This is the case for almost all javascript examples. There’s a form with one text and one password element. When you click “submit form” it has an onsubmit handle that indicates what javascript function to run when someone hits that form. This is similar to the Submit button from earlier in the class. You have the onsubmit that calls a function. What that function does you see in the javascript file.
We did this in the last couple of examples. We get elements by their ID. We get username and password elements based on their ID’s. Those are stored in two variables. One called username EL (element) and password EL (password element). Here I say create a message variable equal to the value of the text input of the username. And password is the password value you entered. This is how you access the value into a text or password input. You say input element value and the Javascript will grab the information for that form.
So this is the same idea as the other examples we’ve seen. Get elements by ID using the getelement by ID
Student: Why not use the username. What’s the purpose of the document. get?
Professor: We have to get Java’s interpretation. Because we want to find the value of it. The sub-property of the element. To get that value we need a function that requires an ID. We give it the ID of the XHTML we want to implement. That’s really the only way to get the element. So it gets the element and puts it in memory.
There’s no such “get Number.” We can access the sub-properties of EL because we stored that object to the variable memory. We can get the height, width, color, style because we told javascript which element to get by indicating the ID of the element.
There’s only this function really this is a special function. It has an XHTML object if we give it an ID.
Ok. Then we just get one specific property of that element, the value property. Before it was class name, font, etc. This is just one property an element may have in the text field.
It’s how the text field works in Javascript. You access the value of the property. Then we pop up this message. So that’s all this function does. It gets the value of the elements and pops it up in the box with the built in javascript function called “Alert.”
One more thing I want to show you. Onsubmit is not just calling this element. It is calling the function but it also has the word “Return” in front of the function. This gets un-intuitive. You see I return something here. This is a return value. So when you call the function think of the function almost like a variable. It’s replaceable by a value. I. and ten are the same thing. The value of variable i Is 10. If I return false it means the function call is replaceable with “false.” The value of the function is false. After it’s run through the function it’s replaced in the script. If I return the number 10 here [On screen.] That means when the function is called here that the function call reference is replaceable by 10. They’re equivalent.
By returning false we’re doing something special. We’re returning the word “false” here and the function gets a value that is ultimately “False.” This tells the onsubmit event of the form to NOT submit the form or to process the data to the server. We’re telling them the submit will not go through, to not submit the data.
So you asked earlier when you submit if it wipes out the fields.
In this case it does wipe it out. So you have to remember not only do you call a function but you put the word return in front of it. If I return true it means on the other page where it’s called it equals to the term true which tells the server to submit the form. There’s two options. Saying true submit or false, cancel the form. This is a common technique in javascript to not submit the form to the server.
So this is how you capture input from text fields. The return of the form is secondary. The first lesson is to access the data.
I’ll move onto another example.
This does the same thing for a text area. So I’ll run through form elements to show you how to get the value of the form.
So I enter text in here. [On screen.] And click submit. You can tell that Java got a value of the text field. Similar to the single line text field. So the HTML has a form and text area and submit button. When you click the submit the on submit handle has an almost identical call. The function returns false. At the end it cancels the form. But before that it gets the text area by getting it’s ID and stores it in “text Area.” Then it attachés the value to that text and it pops up in the other box. It’s the same as the last example.
It’s just what the value property is of that form. So these examples show you the two elements behave the same way.
So the next example will show … radio buttons. Now we show in code how to detect which option. How difficult is this class? Easy right. You selected difficulty level 1. If I select “2″ it tells me I selected 2. So it knows which I picked. The way that works …. like everything else we go to HTML first. We have a form and a bunch of radio buttons and submit. That’s the set up.
Each radio input button has a value associated with it as an attribute. So you see that right? For each there’s a value. 1-4. That’s an XHTML attribute of the radio button type. When you submit the form like the other examples we call this function “show radio value.” So this is important. The values detect the options.
Student: The action called?
To the left?
Professor: That indicates where the data is when a form is submitted.
If I entered in the New York Times site, when I click submit, it sends the data to the New York Times. We cancel that. The pound sign tells it it’s a dummy form. What that actually does is points to the top of the page. When we click the form, it jumps us to the top of the page. It’s a shortcut to the top of your own document.
When I submit the form, that function is defined in the JavaScript file. [On screen.] ShowRadioValue is what we’re calling it. That’s the function that gets called when you click the submit button.
This variable and selectedRadioButtonValue is selected equal to some other function. We’re saying to call this function getRadioButtonValue. Whatever value that function returns, gets put there and placed into selectedRadioButtonValue.
This bottom code section loops through all of the radio buttons and figures out if anything has been checked. It goes through the radio buttons one by one and sees if the checked property is true or not. If it’s checked, that’s the value we get.
You can go through the codes and see how the loop is happening. That’s a for loop. It starts at zero and continues until we reach the number of buttons on the page. It increments by one each time. It checks the check property of each form button. If that property is true and checked, it sets the selected value to that button’s value. It returns the one that has been selected. Then it gets placed up top and stored into the value.
Then we have a message that you have selected whatever the value is you selected. It pops it up in an alert box. This bottom code section is what you do to get the value of a radio button. If there are five buttons, it goes through all five and returns the value of what’s been checked.
That’s how you get the value of a radio button. Next time you want to do that, copy and paste this code and it’ll work for you.
The next example is how to detect the checkbox. You can see if the box has been checked. If I click it, it has been checked. If I unclick it, it comes up as false. Let’s look at that code.
[On screen.] I have an input tag here. It has an ID, checkme. It has an onclick event handler. When I click the checkbox, this function is called. That function is defined in the external style JavaScript file. It does a very similar thing to the functions we’ve already seen. It looks for the element with the checkme ID. It stores it in the variable el. It checks to see if el has been checked or not. If it’s checked, it stores true in the variable.
This evaluates to either true or false as the property. If it’s checked, it’s true. If it’s not checked, it’s false. Then it pops open the value of true or false. The point here is the dot-checked property of any check element holds the property of whether that’s been checked or not.
There’s one more thing. There’s the select input. Click on that. The select state option pops an alert when you click one. It says you selected New York or New Jersey. There are only three options. Somehow it detects which select buttons you selected. That happens in the HTML.
[On screen.] Each option in this select section down at the bottom of the screen has a value. The value for the New York option is NY. The value for New Jersey and NJ. That’s the value that’s detected. It’s not the text that shows on the page. There’s what’s visible and then the behind the scenes details. We’re interested in what’s behind the scenes.
Let’s look at the JavaScript for this. We haven’t seen the onchange attribute before. Anytime you change an option or a different select option has been used, that’s what the onchange event detects. It calls a function to showSelectedState. The onchange is a select data. It detects if it’s changed the selected value. It calls the function showSelectedState.
[On screen.] The first thing it does in JavaScript is get the select object, not the option object. This is the ID I’ve associated with select tag. It gets it by its ID. It stores the element in the selectEl. It’s the element variable representing the selected HTML. Then it gets the value property of that element. It’s like text area and password field, etc. The dot-value property of a select option is the same thing. It’s the value of which one has been selected. It stores that value in the selected state. It assembles a message to pop up. It alerts.
If nothing is selected, the selection value is blank. So we’re checking to see if the value is a blank string. If that’s the case, no one has selected anything. Then we change the message to be something like “please select the state.” Then we pop open the message.
That’s how we get behavior like this. If I select the top choice, it’s blank. This will trigger the “please select a state message” because there’s no value for it. You can look at the HTML and look at the first option. There’s blank quotes. That’s how I detect that nothing has been selected. Or they selected an option that’s not really an option.
We’re clicking the option and looking to see if it’s blank. If it’s not blank, we show the appropriate value.
That was all for the form inputs. Now you have a fun assignment to keep you occupied. Any questions about this so far?
Student: Is there a place we can look up to get the events or anything attached to the elements?
Professor: It’s not easy to find a good reference in books or websites. There is the W3 school site. That’s our major reference. I encourage you to look around at information online and see if it works. W3 School is a reliable source. There is a “learning JavaScript” section. Click on that. You’ll get to a similar thing we saw for the CSS. I encourage you to use the tutorial. It’s not the best but it’s better than most. JavaScript is notoriously badly documented. There’s so much information that has people’s mistakes including books.
It’s difficult to get good information about how it’s used in real life. This tutorial has the same problems. It gives you concepts but not real-life uses. I hope to show you real-life uses. So let’s look at the references. We’ll try the JS HTML section. That’s no good.
Somewhere there’s a list of events. They go into the same things I covered with variables, if/else statements, functions, while loops, for loops, etc. This is a good reference page for what we discussed. There’s also stuff I didn’t discuss but don’t get caught up in it. JavaScript is a huge language. We’re focusing on the practical applications of JavaScript and how to get a job done or a website built. I’m focusing on a subset of what’s on this list. Don’t get too bogged down into the “horror” that is JavaScript.
Student: Look at the first reference on the left. It’s on the last line.
Professor: So go to “learning JavaScript” and click the JS objects and references section on the bottom left. At the top there’s JS events link. I have a post that’s linked to it on my blog that I’ll publish with your homework assignment. That brings you to this page, too. This has different event handlers. This is how you create interactions with users. Use the event handlers to trigger actions. There aren’t that many of them. They’re pretty intuitive.
I want to reiterate that things like onsubmit only apply to form elements. Some are specific to tags. But onmouse, onclick, etc., are generic.
Without further ado, let me show you your homework assignment. I guess it’s the in-class assignment. I’ll publish that post on my blog. It has the link for the homework assignment now. Click that link to “this assignment.” It takes you to the appropriate post of a diagram you should create.
This is a wireframe diagram. Do a simple layout. Redo some of the layout concepts we did before. Create two boxes side by side. Each box has a separate form. When you enter text in any field, the populates the text on the other form. If I type my name in the left box, it fills my name into the right box.
So you’ll detect that someone is entering text. And then you’ll input the value into the right-hand form. I’ll show you how to detect. I haven’t shown you how to input that text.
Student: As I type, it should mirror it at the same time?
Professor: Yes, letter for letter. Each time you hit a key, the right-hand box will show the same key. Every time I touch a key when I’m editing this text field, the onkey press and upkey events are called. That runs a function that inputs value into the right-hand box. It’s the same with the other fields. Text the key and then put the value into the right-hand box. This deals with value properties of the text fields.
Get the element by its ID. Something-dot-value gives us the value. You can set that value property, too. I can say the element.value inputs the text. That’s how you put the text into the right-hand box. When you get there, just raise my hand if you need help. The first part is straightforward. Layout the page and get the fields where they should be. Then do the function calls when someone inputs text.
For the second half, flag me down if you need help. It’s close to lunch, so work for 15 minutes and then we’ll take a lunch break.
[Students working.]
Don’t forget to take a lunch break. It helps to step away from the computer.
[Break]