Beginning Javascript
Beginning Javascript
Up next, Javascript! We use Javascript for client side programming. It is a great way to make our webpages more interactive by dynamicly changing content and styles, as well as verifying input data such as forms. We can even combine javascript with PHP and XML to interact with the server and fetch database information (AJAX). Before we can do any of that, we need to be able to understand the syntax of how Javascript is written.
First, javascript must always be in <script> tags in our HTML, just like how we setup our <style> tags. Also like styles, this will go in the head of your document. So create a new html file, and add this into the <head> of your document.
<script type="text/javascript"> </script>
The type attribute (again just like when using stlyes) ensures the browser knows how to interpret the code. All of the following code we write will go in between these tags.
Comments:
Comments are used to indicate instructions to yourself or another developer. The code will never be run so you can put anything inside the comments. There are two ways to write a comment. For a single-line comment, simply begin with two forward slashes (//). For a comment with multiple lines, begin with a forward slash and asterisk (/*) and end the comment with an asterisk and forwardslash (*/) for example:
//This comment is good as long as it is on one line /* This comment can be as many lines as we need to describe our code */
It is a great idea for beginners to comment each section of code to describe what certain functions / lines of code do for future reference.
Variables
Think of variables as a container of data. There are many content types that can be stored in a variable, we will mainly be dealing with strings, numbers, and booleans. A string will always be wrapped in quotation marks, a number will not. A boolean means the data will be true or false. When we initially write the variable, we must use the prefix "var" before we set the variable. The variable name can be anything we want to call it. It's a good idea to give the name something useful, so when you see it in your code later on, you know what it does:
var myname = "Barney"; var myage = 30; var amtired = false;
We have defined the three types of variables I mentioned. The variable called myname contains the value "Barney". Because we want the text to be read literally as a string we need to wrap it in quotes. Next we make a number variable called my age. Finally a boolean to detect if someone is tired (true or false). With these variables defined, we can change the values later if we want and make new variables as well. (Add this under the previous code):
var othername = "Frank"; myname = othername myage = myage+5; amtired = true;
Here we create a new string variable called othername. Then we change the value of myname to be whatever the value of othername is. (Note that we didn't put "var" before myname this time since it is already defined. Then we tell myname to equal whatever the variable othername is. We don't want to put quotes around "othername" or else the value of the variable will literally say "othername". Currently the value of myname will equal "Frank"). Next, since myage is a number variable, we are able to apply mathematical functions to it. We essentially are telling myage to become whatever the current value of myage is +5 (The value will now be 35). Then we simply change the value of the boolean variable from true to false.
Writing and Alerting
Up to this point, we have no way of knowing if anything we have done is correct. An easy way to do this is write something to the screen. The first way is by using the document.write() method:
document.write("Hello There");
Another way of outputting a message to the user or yourself is by using the alert() method:
alert("Hello There");
Save and test your document, you should see this message appear in two different ways: The document.write message will write the text on the actual page where the alert message will pop up in a box. With an understanding of these functions, we can use them to tell us certain variable values so we can make sure they are correct:
alert(myname);
With this written after the previous code, it should pop up a box saying "Frank". Even though we originally defined myname as "Barney", we later set the value of it to equal whatever the value of othername was.
Creating and using a custom function
A function is a container of code that can be run as many times as we need to, whenever we need to. Just like a variable, we need to define a function first (this time, with the word "function" and can also call it whatever we want). A function must also always contain an opening and closing parenthesis and opening and closing set of brackets:
function buttonpress(){
alert("You pressed a button!");
}
So now whenever we call the function "buttonpress()", it will pop up an alert box that says "You pressed a button". So with our function defined, add this code somewhere in your <body> tags so there is an input button on the page, clicking this button will call the function because of the onclick attribute we add to it:
<input type="button" value="Click Me" onclick="buttonpress()" />
Save and open this up in a browser to test it out. Clicking the button should open an alert box.
Function Parameters
Remember those opening and closing parenthesis "()" as part of the buttonpress function? What we can do is stick an undefined variable in there and every time we call the function, pass a new value for that variable. This is especially important if you want very similar code to run multiple times, where only something small has changed.
Lets create a new function (you can add this below the end bracket of the first function):
function sayhowdy(toname){
alert("Howdy there "+toname+"!");
}
Yikes! What's going on here? Well we created a new function called "sayhowdy", but this time we put the name of a variable (toname) inside those parenthesis. This is the first time the variable is used, we created it and can call it whatever we want to, so we call it "toname" because it will contain the name we will be saying howdy to.
Okay so then we have an alert method being used, but whats with all the plus symbols? What we are doing is concatenating (combining) the string "Howdy there " with whatever the value of toname happens to be. We then concatenate that once more with an exclamation mark. So if the value of toname is equal to "Jeff", the alert will read "Howdy there Jeff!". Neat, let's try it out, add the following two buttons in the body underneath your previous button:
<input type="button" value="Mike's Button" onclick="sayhowdy('Mike')" />
<input type="button" value="Sarah's Button" onclick="sayhowdy('Sarah')" />
We are using these buttons to call the same exact function, the only thing we are changing is the "toname" variable. By passing the string "Mike" or the string "Sarah", you can make the text read "Howdy Anything you want!"
If Statements
Just as it sounds, an if statement checks to see if something is true. If it is, then we can do some sort of code, if it isn't true, then we can do something else. After your functions add the following:
var mycolor = "red";
if(mycolor == "blue"){
alert("I like that color too!");
}
This is the syntax of an if statement in its simplest form. It looks very similar to a custom function doesn't it? Instead of our variable in the parenthesis there is a condition we are checking for. Javascript will evaluate the condition and see if it is true or false. If the condition is true, then the code in the brackets will run. If the statement is false, the code will be ignored. So if you test out your file now nothing new will happen. You can change the value of mycolor to "blue" instead if you want and should see the alert pop up.
One more important thing to note here is the importance of the double equals sign "==". The double equals is used to evaluate that something "is equal to" something else, whereas a single equals symbol "=" tells something to "become equal to" something else. So always be sure to use double equals when using an if statement!
We can make this more advanced by adding on another if statement. Let's say we want to check if it's blue, purple or orange, and if it is neither of the two then we are going to yell at the user for not liking our colors. Let's try it out (you can either comment out or delete the previous if statement, be sure to keep the var mycolor though):
if(mycolor == "blue"){
alert("I like that color too!");
}else if(mycolor == "orange" || mycolor == "purple"){
alert("That color isn't bad also");
}else{
alert("WHAT IS WRONG WITH YOU??");
}
So a few new things; we start out as we did before, checking to see if the color is equal to blue, but now right after the ending bracket "}" we add the word "else" and add another if statement. You can add on as many if statements as you need this way. The next new item is the "||" operator in the middle of the if statement. This stands of "OR". So if our color is "orange" OR "purple" then the result will be true.
We end that statement with one last "else" but this time don't add an if statement to it. We are basically saying "If none of these above are true, do something else" and it runs what is between those brackets. So give this a shot, change the value of mycolor to see what you get.
For Loops
When programming, you will end up doing a lot of repeditive tasks, however there are usually ways around scripting everything by hand. Imagine you had a counter on your website that counted to one hundred, would you really have to write line by line each number? Of course not, we can write a loop to count to one hundred for us. The for loop looks a bit scary at first because there are three separate sections that go into the parameter area. Let's take a look at one and go over what each part is doing:
for(var i=1; i<=100; i++){
document.write(i);
}
So the structure of this seems familiar, we begin with the word "for", have a bunch of stuff in between parenthesis, an opening and closing bracket containing a write function where we are writing the value of variable "i". But what is "i" and what is all that stuff above it?
A for loop contains three separate sections: First it defines a variable to use as a start value (i). We set that value to be 1 since we want the counting to start at 1. The next section is our condition, how long do we want this to keep looping for? We want "i" to keep increasing after each loop (1,2,3,4...) so we know we will reach 100 loops once the value of i is 100. The operator we used to check this is "<=" which means less than or equal to. So the loop will continue as long as the value of i is less than or equal to 100. Lastly, we need to make sure that every time we loop, i is incremented (current value + 1). The "++" operator means to take the current value and add one to it.
So pretty much we create a new variable (i) and set it to start at 1. The loop will run, and every time it does it will increase the value of i by 1, the loop will continue as long as i is not greater than 100.
You can take a look at some other examples / demonstrations of these functions here:
Variables - http://w3schools.com/js/js_variables.asp
If Statements - http://w3schools.com/js/js_if_else.asp
For Loops - http://w3schools.com/js/js_loop_for.asp







