Monday, 1 August 2011

Part 1 - Introduction | XML

XML was designed to transport and store data.
HTML was designed to display data.

XML  What You Should Already Know

Before you continue you should have a basic understanding of the following:
  • HTML
  • JavaScript

XML  What is XML?

  • XML stands for EXtensible Markup Language
  • XML is a markup language much like HTML
  • XML was designed to carry data, not to display data
  • XML tags are not predefined. You must define your own tags
  • XML is designed to be self-descriptive
  • XML is a W3C Recommendation

XML  The Difference Between XML and HTML

XML is not a replacement for HTML.
XML and HTML were designed with different goals:
  • XML was designed to transport and store data, with focus on what data is.
  • HTML was designed to display data, with focus on how data looks.
HTML is about displaying information, while XML is about carrying information.

XML  XML Does not DO Anything

Maybe it is a little hard to understand, but XML does not DO anything. XML was created to structure, store, and transport information.
The following example is a note to Tove from Jani, stored as XML:
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The note above is quite self descriptive. It has sender and receiver information, it also has a heading and a message body.
But still, this XML document does not DO anything. It is just pure information wrapped in tags. Someone must write a piece of software to send, receive or display it.

XML  XML is Just Plain Text

XML is nothing special. It is just plain text. Software that can handle plain text can also handle XML.
However, XML-aware applications can handle the XML tags specially. The functional meaning of the tags depends on the nature of the application.

XML  With XML You Invent Your Own Tags

The tags in the example above (like <to> and <from>) are not defined in any XML standard. These tags are "invented" by the author of the XML document.
That is because the XML language has no predefined tags.
The tags used in HTML (and the structure of HTML) are predefined. HTML documents can only use tags defined in the HTML standard (like <p>, <h1>, etc.).
XML allows the author to define his own tags and his own document structure.

XML  XML is Not a Replacement for HTML

XML is a complement to HTML.
It is important to understand that XML is not a replacement for HTML. In most web applications, XML is used to transport data, while HTML is used to format and display the data.
My best description of XML is this:
XML is a software- and hardware-independent tool for carrying information.

Part 6 - Forms & Functions | JavaScript

Introduction


In part 6 I showed you how to use If and loops. In this part I will show you how you can manipulate HTML forms with JavaScript to improve your website.

Changing The Value Of A Text Box


Before you can manipulate text boxes you must first know how to create a form and how to create a text box in HTML. I will quickly explain this.

Forms for JavaScript are slightly different to standard ones as they do not require any information or script to handle them. You can do everything by just giving the form a name (although later you may want to add the other information so that you can also have the form submitted):


 <form name="formname">
 </form>

In this form you can place a text box using:


<input type="text" name="boxname">


Once you have this you can create your first JavaScript to refer to a form:


Move the mouse over here to add some text to the box

This is done very easily using the onMouseOver property of the link. It can refer to the text box as follows:


 window.document.example1.first_text.value='Hi there';

This tells the browser to put 'Hi there!' into the value of the item called 'first_text' in the form called 'example1'.

You can also do this with multiline text boxes. You can use
/n
to start a new line.

In this section, you have learnt the most important part of this lesson, how to refer to an item in a form.

Events


Just like links, you can set events for items in a form. They are:

onBlur - Happens when the cursor is moved out of the field
onFocus - Happens when the cursor is moved into the field
onChange - Happens when the field is changed and the cursor moves out of it

These are placed into the code as part of the form's item for example:


 <input type="text" onBlur="dothis">

Using The Submit Button


The most common use of forms is to submit data to a script so that it can be processed. This is fine if you are using CGI to do a mailto form or something like that, but if you just want to run a piece of JavaScript from a form you will need to do things a little differently. The first part you must learn about is the return false; attribute. It can be used as follows:


 <form name="myform" onSubmit="return false;">
 <input type="submit" value="Submit">
 </form>

You can try it out below:


What this code does is tell the JavaScript that when the form is submitted it should do nothing. This stops Netscape from refreshing the page (as it would do if there was just a submit button and the form had no action). Now what you can do is to call a function using the submit button:


 <form name="myform" onSubmit="MyFunction(); return false;">

Which will tell the browser to run the function 'MyFunction' when the Submit button is clicked. You can, of course, use this without the:

return false;

part. This would be useful if, for example, you want to validate a form before it is sent to a CGI script. You would include the form's action as normal. Then, in the onSubmit part you would call your function to check what had been entered.

Checkboxes


Checkboxes and radio buttons are two of the remaining form items. First I will cover checkboxes.

Checkboxes have two possible values:

Unchecked Box
Checked Box


As there are only two possible values, the JavaScript to refer to a checkbox is slightly different to that of a text box. In the example below the checkbox has been given the name my_checkbox and is in the form example1.


 if(window.document.example1.my_checkbox.checked=true)
 {
 alert('The box is checked!')
 }
 else
 {
 window.document.example1.my_checkbox.checked=true;
 alert('The box was not checked so I have checked it!');
 }

I will now explain what this code does. It will check the value of the checkbox. If the value is ture (which means the checkbox is checked) then it will display an alert box which will tell you the box is checked. If it is not checked it will check the box (put a checkmark in it) and tell you what it has done.

If, of course, you want to check or refer to the unchecked value of a checkbox the code would be:


 window.document.example1.my_checkbox.checked=false;

Remember that, when refering to check boxes you do not need to inclose true or false in quotations.

As with all other form objects you can use onBlur, onChange and onFocus.

Radio Buttons


Radio buttons are usually found in groups like this:

Blue
Red
Green


Only one button in the group can be checked at a time. Radio buttons work in exactly the same way as a checkbox, having a .checked property which can either be true or false.

Selects and Menus


The two remaining form elements are selects and menus. I will cover menus first. Menus are drop down boxes with several options in them (they are mainly used for things like selecting your country on a form). Selects are really just menus with multiple lines and scrollbars. To show how they work I will show you a quick example of a menu in action and the code for it. For a select box I would just change the height propery. The code used is below:


 <form name="go" onSubmit="return false;">
 <select name="select" onChange="window.document.location=window.document.go.select.value;">
 <option value="#" selected>Please Select</option>
 <option value="http://www.microsoft.com">Microsoft</option>
 <option value="http://www.yahoo.com">Yahoo!</option>
 <option value="http://www.gowansnet.com">Gowansnet</option>
 </select>
 </form>

What this code is doing is, when the select is changed it is telling the page in the browser to change its location to the value of the select box. The location of the document is accessed using:


 window.document.location

As you can see, this is could be very useful, both for getting feedback from visitors and for redirecting them (as in the example above).

JavaScript Functions


JavaScript functions are very useful, and this seems an appropriate place to introduce them. They are pieces of JavaScript which can be declared at the top of your page and can then be referred to again and again in your code. You can even pass parameters to them and make them do different things.


Functions take the following form:



 function functionname(parameters)
 {
 
 }

For a very basic function you need no parameters and it would be constructed like this (in the <head> of the document):


 function sayhi()
 {
 alert(Hi there!);
 }

Then, anywhere in the text you could place this:


 <a href="#" onMouseOver="sayhi();">Say Hi</a>

Which would display the alert whenever the mosuse passed over it. Unless you are repeating something many times, though, this will not seem particularly useful. This is where parameters become useful.

Parameters


Parameters are a very useful part of functions. They allow you to pass data to the function when it is called. Here is an example:


 function say(what)
 {
 alert(what);
 }

in the head, then:


 <a href="#" onMouseOver="say(hi);">Say Hi</a>
 <a href="#" onMouseOver="say(bye);">Say Bye</a>

What this is doing is the information in the brackets is passed to the function. In the brackets of the function is the word 'what'. This is telling the JavaScript to assign the information in the brackets to the variable what (the same as var what='something';). You can even do this with multiple pieces of information by separating th
em by commas.

As you can see functions and parameters are very useful.

Part 5 - Date | JavaScript

JavaScript Date and Time Object

The Date object is useful when you want to display a date or use a timestamp in some sort of calculation. In Java, you can either make a Date object by supplying the date of your choice, or you can let JavaScript create a Date object based on your visitor's system clock. It is usually best to let JavaScript simply use the system clock.
When creating a Date object based on the computer's (not web server's!) internal clock, it is important to note that if someone's clock is off by a few hours or they are in a different time zone, then the Date object will create a different times from the one created on your own computer.

JavaScript Date Today (Current)

To warm up our JavaScript Date object skills, let's do something easy. If you do not supply any arguments to the Date constructor (this makes the Date object) then it will create a Date object based on the visitor's internal clock.

HTML & JavaScript Code:

<h4>It is now  
<script type="text/javascript">
<!--
var currentTime = new Date()
//-->
</script>
</h4>

Display:

It is now

Nothing shows up! That's because we still don't know the methods of the Date object that let us get the information we need (i.e. Day, Month, Hour, etc).

Get the JavaScript Time

The Date object has been created, and now we have a variable that holds the current date! To get the information we need to print out, we have to utilize some or all of the following functions:
  • getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM
  • getSeconds() - Number of seconds (0-59)
  • getMinutes() - Number of minutes (0-59)
  • getHours() - Number of hours (0-23)
  • getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
  • getDate() - Day of the month (0-31)
  • getMonth() - Number of month (0-11)
  • getFullYear() - The four digit year (1970-9999)
Now we can print out the date information. We will be using the getDate, getMonth, and getFullYear methods in this example.

HTML & JavaScript Code:

<h4>It is now  
<script type="text/javascript">
<!--
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
//-->
</script>
</h4>

Display:

It is now 6/18/2009 !

Notice that we added 1 to the month variable to correct the problem with January being 0 and December being 11. After adding 1, January will be 1, and December will be 12.

JavaScript Current Time Clock

Now, instead of displaying the date we, will display the format you might see on a typical digital clock -- HH:MM AM/PM (H = Hour, M = Minute).

HTML & JavaScript Code:

<h4>It is now  
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
document.write(hours + ":" + minutes + " ")
if(hours > 11){
document.write("PM")
} else {
document.write("AM")
}
//-->
</script>
</h4>

Display:

It is now 13:59 PM

Above, we check to see if either the hours or minutes variable is less than 10. If it is, then we need to add a zero to the beginning of minutes. This is not necessary, but if it is 1:01 AM, our clock would output "1:1 AM", which doesn't look very nice at all!

Part 4 - Loops and Arrays | JavaScript

JavaScript Loops

Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript, there are two different kind of loops:
  • for - loops through a block of code a specified number of times
  • while - loops through a block of code while a specified condition is true

While Loops


While loops are pieces of code which will repeat until the condition is met. This is very useful for things like passwords when you want to keep asking the user until they get it correct. For example this code will repeat until the user enters the word 'hello':


 var password = 'hello';
 var input = prompt('Please enter the password', '');
 while(input != password)
 {
 var input= prompt('Please enter the password''');
 }

This will continuously loop the code inside the { } until the test input does not equal password is false (the password is correct).

For Loops


For loops are used to do something a set number of times. For example:


 for(loop=0; loop < 11; loop++)
 {
 
 document.writeln(loop);
 }

This will start by setting the variable loop to 0, it will then loop, adding one to the value each time (using the loop++ code) as long as loop is less than 11. They take the form:


 for(starting value; test; increment)

These have many uses.

Arrays

What is an Array?

An array is a special variable, which can hold more than one value, at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Saab";
$cars2="Volvo";
$cars3="BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The best solution here is to use an array!
An array can hold all your variable values under a single name. And you can access the values by referring to the array name.
Each element in the array has its own ID so that it can be easily accessed.

Create an Array

The following code creates an Array object called myCars:
var myCars=new Array();
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
You could also pass an integer argument to control the array's size:
var myCars=new Array(3);
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2:
var myCars=new Array("Saab","Volvo","BMW");
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]);
will result in the following output:
Saab


Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
Now, the following code line:
document.write(myCars[0]);
will result in the following output:
Opel

Part 3 - Operators & IF Statements | JavaScript

JavaScript Operators

= is used to assign values.
+ is used to add values.

The assignment operator = is used to assign values to JavaScript variables.
The arithmetic operator + is used to add values together.
y=5;
z=2;
x=y+z;
The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Operator Description Example Result
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4


JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
Operator Example Same As Result
= x=y   x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0


The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains "What a verynice day".
To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the variable txt3 contains:
"What a very nice day"

Adding Strings and Numbers

The rule is: If you add a number and a string, the result will be a string!

Example

x=5+5;
 document.write(x);
 x="5"+"5";
 document.write(x);
 x=5+"5";
 document.write(x);
 x="5"+5;
 document.write(x); 
 

If Statement

If


The if function allows you to check to see if something is true or false. For example you could check to see if text entered by a user matches a piece of text you already have (like a password). To show if in action click here.

As you can see this could be very useful for many sites. The code is as follows:

 var guess = prompt("Please guess a number between 1 and 10","");
 if(guess == 5)
 {
 alert('Correct! I was thinking of 5');
 }
 else
 {
 alert('Wrong! I was thinking of 5');
 }

This code is made up of three main parts. The first part which gets the guess from the user, you have used before. This is followed by:

 if(guess ==5)

Which is quite self explanitary. It checks to see if the variable guess is equal to 5. The if statement is followed by:

 {
 alert('Correct! I was thinking of 5');
 }

The important part of this is the curly brackets round the alert command. These contain the code which should be executed if the if statement returns 'true' (in this example if guess equals 5). The final part is the:

 else
 {
 alert('Wrong! I was thinking of 5');
 }

This tells the browser that if the if statement does not return 'true' (in this example if guess does not equal 5) to execute the code between the curly brackets.

Together this code makes up the if statement.

More If


There are other conditions you can test with the if statement. Firstly, as well as using numbers you can compare variables or text:

 if(variable == variable)
 
 if(variable == "some text")

As well as doing this you can check to see if one variable is greater than another, less than another or not the same as another:

if(variable < othervariable)
If variable is less than othervariable

 if(variable > othervariable)
If variable is greater than othervariable

 if(variable <= othervariable)
If variable is less than or equal to othervariable

 if(variable >= othervariable)
If variable is greater than or equal to othervariable

 if(variable != othervariable)
If variable is not equal to other variable

These can be very useful in your web pages. You can also check to see if two conditions are true before executing code using &&:

 if(variable1 == variable2) && (variable1 < variable3)

This will only execute its code if variable1 is equal to variable2 and is less than variable3. You can also run the code if one of the conditions is true:

 if(variable1 == variable2) || (variable1 < variable3)

This will only execute its code if variable 1 is equal to variable to or is less than variable3.

Else If Statement

In the previous lesson, you learned how to create a basic If Statement in JavaScript, which is good enough for most programming situations. However, sometimes it is helpful to have the ability to check for more than one condition in a single If Statement block.
The Else If statement is an extension to the If Statement that allows you to create as many checks (conditional statements) as you want in one big block of If Statement code.

JavaScript Else If Example

Imagine that you want to have a small "student" script that will print out a customized message depending who is accessing the webpage. If you have more than two custom messages, you could use the Else If extension to solve this programming problem.

JavaScript Code:

<script type="text/javascript">
<!--
var visitor = "principal";
if(visitor == "teacher"){
 document.write("My dog ate my homework...");
}else if(visitor == "principal"){
 document.write("What stink bombs?");
} else {
 document.write("How do you do?");
}
//-->
</script>

Display:

What stink bombs?
There are two important things to note about the Else If extension:
  1. You must have a normal If Statement before you can use the Else If statement. This is because the Else If statement is an addon to the If Statement.
  2. You can have multiple Else If add-ons. In our example, we only used one Else If extension, but you can add as many as you require.

GA_googleFillSlot('Tizag_Javascript_Content_468x60');

Part 2 - Syntax & Variables | JavaScript

How To Write JavaScript

If you have ever used CSS before, you will find the whole part about including JavaScript will be a lot simpler to grasp. Here are Tizag's three important steps you should always follow when creating or using someone else's JavaScript code:
  1. Use the script tag to tell the browser you are using JavaScript.
  2. Write or download some JavaScript
  3. Test the script!
There are so many different things that can go wrong with a script, be it human error, browser compatibility issues, or operating system differences. So, when using JavaScript, be sure that you test your script out on a wide variety of systems and most importantly, on different web browsers.

Your First JavaScript Script

To follow the classic examples of many programming tutorials, let's use JavaScript to print out "Hello World" to the browser. I know this isn't very interesting, but it will be a good way to explain all the overhead required to do something in JavaScript.

HTML & JavaScript Code:

<html>
<body>
<script type="text/JavaScript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

Display:

Hello World!
Our first step was to tell the browser we were using a script with the <script> tag. Next we set the type of script equal to "text/JavaScript". You may notice that doing this is similar to the way you specify CSS, which is "text/css".
Next, we added an optional HTML comment that surrounds our JavaScript code. If a browser does not support JavaScript, it will not display our code in plain text to the user! The comment was ended with a "//-->" because "//" signifies a comment in JavaScript. We add that to prevent a browser from reading the end of the HTML comment in as a piece of JavaScript code.

JavaScript document.write

The final step of our script was to use a function called document.write, which writes a string into our HTML document. document.write can be used to write text, HTML, or a little of both. We passed the famous string of text to the function to spell out "Hello World!" which it printed to the screen.
Do not worry if you don't completely understand how document.write works, as we will be discussing functions in a later lesson.

Syntax

Looking at our JavaScript code above, notice that there is no semicolon at the end of the statement "document.write(Hello World!)". Why? JavaScript does not require that you use semicolons to signify the end of each statement.
If you are an experienced programmer and prefer to use semicolons, feel free to do so. JavaScript will not malfunction from ending semicolons. The only time it is necessary to use a semicolon is when you choose to smash two statements onto one line(i.e. two document.write statements on one line).

Variables

Do You Remember Algebra From School?
Do you remember algebra from school? x=5, y=6, z=x+y
Do you remember that a letter (like x) could be used to hold a value (like 5), and that you could use the information above to calculate the value of z to be 11?
These letters are called variables, and variables can be used to hold values (x=5) or expressions (z=x+y).

JavaScript Variables

As with algebra, JavaScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname.
Rules for JavaScript variable names:
  • Variable names are case sensitive (y and Y are two different variables)
  • Variable names must begin with a letter or the underscore character
Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Example

A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value.
This example will show you how

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.
You can declare JavaScript variables with the var statement:
var x;
 var carname;
After the declaration shown above, the variables are empty (they have no values yet).
However, you can also assign values to the variables when you declare them:
var x=5;
 var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Volvo.
Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically be declared.
These statements:
x=5;
carname="Volvo";
have the same effect as:
var x=5;
var carname="Volvo";


Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.
var x=5;
var x;
After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it.

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5;
z=y+5;

Part 1 - Introduction | JavaScript

JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari.

What You Should Already Know

Before you continue you should have a basic understanding of the following:
  • HTML / XHTML
If you want to study these subjects first, find the tutorials on our Home page.

What is JavaScript?

  • JavaScript was designed to add interactivity to HTML pages
  • JavaScript is a scripting language
  • A scripting language is a lightweight programming language
  • JavaScript is usually embedded directly into HTML pages
  • JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
  • Everyone can use JavaScript without purchasing a license

Are Java and JavaScript the same?

NO!
Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.

What can a JavaScript do?

  • JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
  • JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
  • JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
  • JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element
  • JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
  • JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
  • JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

The Real Name is ECMAScript

JavaScript's official name is ECMAScript.
ECMAScript is developed and maintained by the ECMA organization. 
ECMA-262 is the official JavaScript standard.
The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all Netscape and Microsoft browsers since 1996.
The development of ECMA-262 started in 1996, and the first edition of was adopted by the ECMA General Assembly in June 1997.
The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998.
The development of the standard is still in progress.
 

E-Learning Copyright © 2011 Powered by Blogger