Sunteți pe pagina 1din 30

Introduction to web design using JavaScript This is a programming language that is used to create programs that can be embedded

to the World Wide Web. JavaScript is an Object Oriented Language Everything in JavaScript takes the form of an object. This means that it is a package, which contains various properties (pieces of information) and methods (lists of instructions that it can carry out).

Terms used in JavaScript Properties These are characteristics of objects in JavaScript. Objects These are controls that are used to design web pages. Methods These are activity related to objects. Events These actions related to an activity performed in JavaScript. JAVASCRIPT APPLICATION Data entry validation. Dynamic HTML interactivity. CGI prototyping. Serverless CGIs Offloading busy server. Adds life to dead pages. For creating web pages that think. Essentials of a JavaScript document <script> Assists the browser to recognize the lines of code in HTML documents. The code should be surrounded in <script> as the starting tag and </script> as the ending tag. Script tag attributes Language= Asks the browser to treat the code as javascript code. <script language=javascript> Statements </script> Src= Points to the file containing the script code. The file must end with .js extension. 1
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

<script language=javascript src=data..js> Statements </script> <head> A place for tags that influence non-content settings for the page called HTML directive elements. <title> Lists the title of the documents. <body> Where the actual contents are placed.

Example 1 <html> <title>javascript</title> <body> <script language="JavaScript"> document.write("Hello there? welcome the world of javascript language."); document.write("<p>"); document.write("This is my first JavaScript program."); </script> </body> </html>

Example 2 <html> <title>javascript</title> <Body> <script language="JavaScript"> document.bgColor = "YELLOW"; </script> You can add some more text and/or HTML tags here, of course. </body> </html> Javascript methods Open() Used to create a new document. Document.open() 2
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

Document.open(new document) Close() Used to close documents created with open() method. Write() Used to insert text into a web browser. Writeln() Writes text to next line in a web browser. Javascript events Onloads Loads a popup window into a web page. <body onload=alert(welcome to any web page)> Unonloads Unloads a popup window from the web page. <body unonload=alert(goodbye-have a nice day)>

Javascript statements These are instructions that execute to give results. Statements in javascript: Initialize or define a variable. Assign a value to a value, a property or a variable.. Invokes a n object. Invokes a function. Invokes a decision. Changes a value of a property or variable.

Javascript programming fundamentals a) Datatypes in javascript They are also values. They show the kind of information to store in variables. Data type String Number Boolean Null Object function Example Howard 4.6 True null Description A series of characters in quotes Any number without quotes Logical true or false Devoid of content A software defined by properties and methods Function definition 3
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

b) Variables A variable represents a piece of data stored in a computer program. All variables have a name and a value. We can think of them as being like small boxes, each of which can contain one item. The name of the variable is how we refer to the box, and the value is the item stored in the box. Variables in JavaScript must be declared before they can be used. They are declared using the word var followed by the variable name and a semicolon.

Var age; Use meaningful words Dont use keywords in javascript. Variables dont have spaces instead use underscores. They must start with a letter. Variable names are case sensitive, which means that the variables names myName, MYNAME and Myname would all refer to different variables. Variables are set to values using an equals sign. Initializing variables Var age=38; c) Expression and evaluation in javascript An expression is a set of operators and operands that are used to perform some calculations and produces results. Evaluating is finding an outcome of an expression.

d)

Operators

A set of symbols that are used to perform an operation.

Types of operators Arithmetic operators + * / Mod ^ Comparison operators > 4


JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

< >= <= <> Operators The most common operators are mathematical operators; +, -, /, * (add, subtract, divide, multiply) for example. Operators can be split into two groups, comparison operators and assignment or 'action' operators. Comparison operators test to see if two variables relate to each other in the specified way, for example, one variable is a higher number than the other. Other operators perform an action on a variable, such as increasing it by one. The following table gives those that are most commonly used. There are many JavaScript 1.3 operators such as the identity operator === and others like it. These are supported by all current browsers, but are rarely used. Browsers that do not understand them will just produce errors. JavaScript operators Operator Uses adds two numbers or appends two strings - if more than one type of variable is appended, including a string appended to a number or vice-versa, the result will be a string subtracts the second number from the first divides the first number by the second multiplies two numbers divide the first number by the second and return the remainder assigns the value on the right to the object on the left the object on the left = the object on the left + the value on the right - this also works when appending strings the object on the left = the object on the left - the value on the right number on the left must be greater than the number on the right - this also works with strings and values 5
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

/ * % = += -= >

JavaScript operators Operator Uses < number on the left must be less than the number on the right - this also works with strings and values number on the left must be greater than or equal to the number on the right - this also works with strings and values number on the left must be less than or equal to the number on the right - this also works with strings and values increment the number decrement the number the numbers or objects or values must be equal the numbers or objects or values must not be equal bitwise leftshift bitwise rightshift AND OR XOR NOT logical NOT (the statement must not be true) logical AND (both statements must be true) logical OR (either statement must be true) object or array on the right must have the property or cell on the left

>=

<= ++ -== != << >> & | ^ ~ ! && || in

JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

Operator precedence If you ask JavaScript to perform a calculation using multiple operators, those operators will be evaluated in a specific order. For example 3 + 6 * 7 is calculated as ( 6 * 7 ) + 3 because the * is calculated before the +. The order in which these are evaluated is: * / % + - + (where the second + is appending strings). To change the order in which they are calculated, use parenthesis ( ) as the contents of parenthesis are calculated before the contents outside the parenthesis. For example, 3 + 6 * 7 = 45 but (3 + 6) * 7 = 63 Example 1 <html> <head> <title>sum of two numbers in javascript</title> <body> <script language="JavaScript"> var first = 12; var second = 4; var sum = first + second; document.write(sum); </script> </head> </body> </html> String variables String variables are textual or a set of strings of characters which are words and sentences. They are enclosed within double quotes. E.g. X=Gusii Institute of Technology Document.write(x); Mixing strings and numbers You can mix numbers and strings together to allow an expression execute. First=100; Second=20; Answer=first+second; Document.write (the answer is:,answer); Javascript Functions

JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

A function is a group of instructions which has been given its own particular name. It can be called at any point simply by quoting the name of the function (with a couple of brackets). Perhaps an example may be useful: A function is a piece of code is referenced or called upon to perform an operation and return a value when called. In addition to controllable execution, functions are also a great time saver for doing repetitive tasks. Instead of having to type out the code every time you want something done, you can simply call the function multiple times to get the same effect. This benefit is also known as code reusability. All you have to do is tell the browser you're making a function, give the function a name, and then write the JavaScript. Functions in javascript have been classified into two: In built functions. User defined functions.

In built functions Prompt() Prompt function displays a box on the screen and asks the user to enter a value. E.g. Y=prompt(enter the value of y); X=prompt (enter the value of x); Example 1 <html> <head> <title>html functions</title> <script language="JavaScript"> var firstnumber = prompt("Enter the first number", ""); var secondnumber = prompt("Enter the second number", ""); 8
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

var answer = firstnumber + secondnumber; document.write("The answer is " + answer); </script> </head> </html> Converting strings to numbers The problem with the prompt() instruction is it always returns a string. If we used it to get two numbers from the user and add them, we are going to run into problems: If you enter 3 for the first number and 3 for the second, you should get the answer 6, but in fact you get the answer 33. Well, the variables firstnumber and secondnumber are set to the string values 3 and 3 which, although they look like numbers are actually strings. The + sign then concatenates them to form a longer string. We convert the string that prompt() gives us into a number. There are two instructions that we can use, parseInt() and parseFloat(). The instruction parseInt() will take a string, either as a constant inside quotation marks or a variable, or even as an expression, and will turn it into a whole number. The 'whole' is important in that - the "Int" part of the instruction stands for "integer", which is the technical name for a whole number. x = parseInt("7"); var digit0 = "0"; document.write(4.55) + parseInt("1" + digit0) + "<p>"); ParseFloat() Well, this is the instruction you would use if you want to convert a whole number to decimal (non whole number) answer. e.g. var x = "500"; var y = parseFloat(x); document.write(y + 100);

Example 2 9
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

<html> <head> <title>html functions</title> <script language="JavaScript"> var firstnumber = parseFloat(prompt("Enter the first number", " ")); var secondnumber = parseFloat(prompt("Enter the second number", "")); var answer = firstnumber + secondnumber; document.write("The answer is " + answer); </script> </head> </html> The eval() instruction Eval() function works in almost the same way as parseFloat(), so it can produce decimal numbers as well as whole numbers. However, it can also evaluate simple mathematics in strings. Take a look at this: var x = eval("2 * 2"); document.write(x); The instruction eval("2 * 2") works out the answer to this calculation and that becomes the value of x. The document.write(x) instruction displays the number 4 on the screen. You can also include variables inside the mathematical expression and they will be evaluated correctly. var tempval = 100; var p = 4.5; var x = eval("tempval - 3 * p"); document.write(x);

The alert() function The Alert() function is an alternative way to display messages, variables, numbers etc. on the screen which grabs your attention slightly more than document.write() does. It is called in a similar manner to document.write(), i.e. the item to be displayed are enclosed within brackets: alert("The answer is " + answer); This produces a grey box on the screen and a bleep noise. The box won't disappear or let you carry on with the program until you click on the OK button.

10

JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

Javascript user defined functions

These are functions created by the users to suite their needs. The function must be defined by: Use of the keyword Function. Assign the function a name. Enclose the instructions/statements in curly brackets; { }. Example 1 <html> <head> <title>html functions</title> <SCRIPT LANGUAGE="JavaScript"> function sum () { answer = a + b + c; } var a = 10, b = 20, c = 30, answer, averageValue; sum(); alert("The sum of the numbers is " + answer); 11

// function definition //

// function call //
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

</SCRIPT> </head> </html>

Example 2 <html> <head> <title>html functions</title> <SCRIPT LANGUAGE="JavaScript"> function average() { answer= (a+b+c)/ 3; } var a = 10, b = 20, c = 30,answer; average(); alert("The average of the numbers is " + answer) main program </SCRIPT> </head> </html> In the first example function adds three variables, a, b and c and stores the sum in a variable called answer. The second example adds the three variables and divides by 3 and stores the result in the variable answer. The MAIN PROGRAM creates the three variables with different values and then calls the sum() function and average(). It displays the value of answer on the screen. The function does any displaying on the screen itself, they just do calculations. Parameters Parameters are memory location that reserves a space for use during execution. The parameters are static.

Example1 <html> <head> <title>html functions</title> <script language="JavaScript"> function sum (first, second, third) { answer = first + second + third; 12

// parameter names;

JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

} var a= 100, b= 200,c= 400; sum(100, 200, 400); alert("The sum is " + answer); </script> </head> </html> Parameter passing Pass by value

// function call;

Parameters Pass-by-value means that values are merely copied and transferred to the calling statement. The fact that parameter values are only ever passed into functions, never out of them, is sometimes referred to as Pass by value. We say that the parameter has scope which is local to the function. <SCRIPT LANGUAGE="JavaScript"> Var x = 40; Alert ("The value of temp is + x); Marks(x); Alert ("The value of x is + x); Function marks(x) {x *= 10; // this multiplies temp by 10; document.write ("Inside the function, temp is + x); } </SCRIPT> Pass-by-reference Parameter pass by references means that values are transferred as a whole and not copied. Modification can also be done to the values.

Variable scope Scope means the extent or accessibility of variables in a program. They are of two types. Global variables This means that variables exist throughout the whole of the JavaScript program. They can be accessed by any statement, function.

<SCRIPT LANGUAGE="JavaScript"> Function Payments () { var x = 5000; 13


JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

document.write (x); } var a = 10; document.write (a); Payments (); document.write ("After the call, a is " + a + "<BR>"); </SCRIPT>

The return statement The return instruction only ever appears inside functions. It is used to pass values out of the function and back to the main program which called it (or to a calling function if it was called from another function). The return instruction is followed by the value to be returned, and it means that the function call can be used in place of a number or string. Example1 <html> <head> <title>html functions</title> <SCRIPT LANGUAGE="JavaScript"> function average (num1, num2, num3, num4) { var sum = num1 + num2 + num3 + num4; Return sum / 4; } var a = 2, b = 30, c = 78, d= 100; document.write ("The average is + average(a, b, c, d) + "<BR>"); </SCRIPT> </head> </html> Example 2 <html> <head> <title>html functions</title> <SCRIPT LANGUAGE="JavaScript"> function sum (a,b,c) { return a + b + c; } function average (a,b,c) { return sum(a,b,c) / 3; } var a = 34, b = 51, c = 60; 14
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

alert("The sum of the numbers is " + sum(a,b,c)); alert("The average of the numbers is " + average(a,b,c)); </SCRIPT> </head> </html> Recursive Functions Functions call other functions or procedures to return values. It is equally possible for a function to call itself. Such a function is called a recursive function.

Factorials are written using the ! Symbol, and are defined as follows: 0!=1(bydefinition) 1!=1 2!=2x1=2 3!=3x2x1=6 4!=4x3x2x1=24 5! = 5 x 4 x 3 x 2 x 1 = 120 To get factorial quickly we multiply the number by the previous factorial, i.e. 5! = 5 x 4! Similarly, 9! = 9 x 8! And 103! = 103 x 102! This means that if you know a factorial you can easily get the next one in the series. Example 1 <html> <head> <title>html functions</title> <SCRIPT LANGUAGE="JavaScript"> Function factorial (n) { if (n == 0) return 1; else return n * factorial(n-1); } // Display all the factorials from 0! to 10! var count; for (count = 0; count < 11; count++) document.write ("The factorial of + count + is +factorial (count) + "<BR>"); </SCRIPT> </head> </html> 15
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

The function takes a parameter and calculates the factorial of that number. Note that the first thing that the function does is test to see if we have reached the lowest number for which factorial is defined. This is the stopping condition of the recursive function and all recursive functions must have one. Suppose it had been missed out: function factorial (n) { return n * factorial(n-1); } Such a function, when called, would never terminate as it would endlessly be calling itself. Javascript control structures a) The if statement This is the simplest way in which we can get a JavaScript program to make decisions. Used to compare two or more values in an expression and return a value. If statement syntax: if (condition) { // Statements to be executed go here // Put in as many statements as you think fit } The condition is a statement which may be true or may be false. If it is true, the statements inside the { } are executed. If the condition is false, the statements aren't executed. Example1 <html> <head> <title>html functions</title> <script language="JavaScript"> var userinput = prompt("Please enter a number","") if(userinput> 100) { document.write("You entered a really big number!"); } </script> </head> </html> Example2 <html> <head> 16
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

<title>selection</title> </head> <script language="text"> var firstnumber = prompt("Enter the first number", ""); if(age>=18) { document.write("you are a grownup"); } if(age<18) document.write("you are young"); } </script> </html>

b) Ifelse statements The statements which follow the else are only executed if the condition fails. In this way, at least one set of statements is carried out - either before the else or after it. e.g. if (a == 6) document.write("The value of a is 6"); else if (b > 10) document.write("b is larger than 10 and a is not 6"); Example3 <html> <head> <title>selection</title> <script language="javascript"> var firstnumber=eval(prompt("Enter the first number", "")); var secondnumber=eval(prompt("Enter the second number", "")); var thirdnumber=eval(prompt("Enter the third number", "")); var sum=firstnumber+secondnumber+thirdnumber; var average=sum/3; document.write("average"+average + "<br>"); if(average>=80 && average<=100) { document.write("DISTINCTION"); } else 17
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

if(average>=70 && average<=79) { document.write("CREDIT"); } else if(average>=60 && average<=69) { document.write("PASS"); } else if(average>=500 && average<59) { document.write("REFFERED"); } else if(average>=40 && average<=49) { document.write("FAIL"); } else if(average<=79) { document.write("REPEAT THE UNIT"); } </script> </head> </html>

b)The switch statement Switch is a variation on the if statement. Instead of having a condition which can be true and false (i.e. the decision can go one of two ways), the value of a variable is tested. The switch statement can then do one of several different things, depending on what the value of the variable is. Points to note about switch statements:

You can only test the value of a simple variable, not an expression. For that reason, a switch statement that started like this: switch (a) { case 25 : // etc. would be perfectly legal, but one that started off as follows: switch (a + b) 18
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

{ case -40 : // etc. would not be. This is because a + b is not a simple variable.

Unlike if statements, where the statements need to be blocked together using opening and closing curly brackets, { and }, the statements that form the parts of the switch statement dont need to be. The starting point for each block of statements is obvious - it is the word case followed by the appropriate value - and the stopping point of the block is equally obvious - it is the word break that instructs the program to skip over the rest of the switch statement. Note which parts of the switch statement require a semicolon and which do not. Like the if statement, there is no semicolon after the variable being tested. The statements making up the cases have semicolons at the end as usual. The word break is optional at the end of each block. However, if you dont include it, the program will not skip to the end when it reaches that point. Instead it will carry on with the statements for the next case.

JavaScript iterative control structures A loop is computer instruction which allows a program to repeat a sequence of statements more than once. There is a special computer term for this - we call it iteration. There are three types of loop in JavaScript, and each has its own specific uses: the while loop, the do-while loop and for loop. Each loop has a starting point in the program and an ending point, and includes either one statement or a whole block of statements. The ++ notation Increase the value of this variable by 1 to keep the loop going. e.g. x = 2; alert(x); // This displays 2 on the screen x++; // Increase x by 1 alert(x); // This displays 3 on the screen

This process of increasing a number by 1 can be done with any variable that holds a number (i.e. a whole number or a decimal number, positive, negative or zero), but it could not be done with a variable that contained a string. 19
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

x = "I am a string"; x++; // This should cause an error! We can adapt the instruction so that it adds on or subtracts numbers other than 1. This is done by putting a plus (or minus) sign just before the equals sign in assignment: first += 10; second -= 23.4; The first instruction here adds on 10 to the value of first, so that its value increases by 10. Similarly, the second instruction decreases the value of second by 23.4. Please note that there is no space between the + or - sign and the = sign. You can also multiply or divide a variable in a similar way by putting a * or / sign directly before the = sign. x /= 10; alert(x); // This displays the value 100; x *= 4; alert(x); // This displays the value 400; You can also use the instruction %= to set a variable to the remainder when that same variable is divided by the following number. Perhaps an example will make that clearer: var x = 79; x %= 5; The while loop This loop specifies a condition at the start, and continues to iterate all the time that the condition remains true. Format of the while loop while (condition) { // Statements forming the body of the loop go here }

Example1 <html> 20
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

<head> <title>selection</title> <script language="javascript"> var x = 2; while (x < 100) { document.write(x + "<BR>"); x +=1; } document.write("The loop has terminated!"); </SCRIPT> </script> </head> </html> The variable x is initialized to 2. When the loop is first encountered, the condition (x<1000) is evaluated. It succeeds, so the loop is executed. The value of x is displayed, and then x is added to 1. Then the condition is tried again, with x now equal to 2. This is still less than 100, so the loop is executed again. The loop carries on executing until the value of x is set to 101. The condition then tests to see whether it is less than 100, so the loop is not executed, and the program continues with the statement after the end of the loop, i.e. the program displays the message "The loop has terminated". The do-while loop

This loop is similar to the while loop, but with one subtle difference. This time, the condition is tested at the end of each iteration of the loop. This means that the loop must iterate at least once. It can never be skipped entirely. Format of the do-while loop do { // Statements forming the body of the loop go here } while (condition); 21
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

In do-while loop, the curly brackets are necessary to enclose the statements. With the other sorts of loops, you can miss out the curly brackets if you only have one statement to include (just as you can with if statements), but with the do-while loop, they are necessary. The following: do x += 2; while (x < 2500); Would be illegal. It would have to be written as do { x += 2; } while (x < 2500); Example1 <html> <head> <title>selection</title> <script language="javascript"> var x = 0; do { document.write(x +"<br>"); x++; } while (x<=10); </script> </head> 22
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

</html>

For loop statement The for loop contains a header enclosed within brackets. There are three parts to the header, separated by semicolons: For loop Syntax For (initialization; continuing condition; increment/decrement operator) { // Statements } The initialization part is a statement which is carried out before the loop is executed. It normally sets a variable to a certain starting value. The continuing condition is a condition tested at the start of each iteration. If the condition is true, then the loop iterates - and carries on repeating until the condition fails. The increment/decrement operator is an instruction that is carried out at the end of each iteration.

Example1 <html> <head> <title>selection</title> <script language="javascript"> for (x =1;x<=100;x=x+1) { document.write(x+"<br>"); } </script> </head> 23
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

</html> This loop starts by setting the variable x to 1. The test is carried out: Is x less than or equal to 100 Yes it is, so the loop is executed. The document.write () statement is executed. The end-of-loop statement is carried out (count++) and the value of count goes up to 1. The whole thing is repeated, and the new value 1 is displayed. Nested loops in javascript It is perfectly possible to include one loop entirely within another. Such loops are known as nested loops. Example1 Create a javascript program which displays multiplication tables, from 1 x 1 = 1 to 12 x 12 = 144 on the screen <html> <head> <title>selection</title> <script language="javascript"> var table = 1; var index; while (table <= 12) { document.write("<P>"); for (index = 1; index <= 12; index++) document.write(index + " x " + table + " = "+ (index * table)+"<br>"); table++; } </script>

24

JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

</head> </html>

JavaScript Arrays These are variables with the same name and data type in a computer memory. Instead of a single variable we have several variables in a memory with the same name and return type.

Declaring arrays var numbers = new Array(); numbers[0] = 41; numbers[1] = -5; numbers[2] = 20; numbers[3] = 0; numbers[4] = 3; numbers[5] = -11; numbers[6] = 37;

There is an alternative way to set the values in the array elements. Just as ordinary variables can be set to values at the same time as they are declared, you can do the same with arrays: var numbers= new Array(41, -5, 20, 0, 3, -11, 37); Example1 <html> <head> <title>selection</title> <script language="javascript"> var numbers = new Array(); numbers[0] = 41; numbers[1] = -5; numbers[2] = 20; numbers[3] = 0; numbers[4] = 3; numbers[5] = -11; 25
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

numbers[6] = 37; document.write([numbers]); </script> </head> </html>

Two- and multi-dimensional arrays The arrays that we have been looking at so far are one-dimensional arrays - the values stretch out in a line. Two dimensional arrays contain both columns and rows.

In this case, since we have rows and columns, we need two numbers to specify an element of the array. Declaring two dimensional Declaring and using two dimensional arrays is done in a similar way to one-dimensional arrays, except that each column of the array must be declared individually. X[0][0] = 34; x[2][4] = 30;

JavaScript animation A motion picture made by photographing successive positions of inanimate objects (as puppets or mechanical parts). A motion picture made from a series of drawings simulating motion by means of slight progressive changes. Animation techniques 26
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

Frame-Based Animation

Frame-based animation is the simpler of the animation techniques. It involves simulating movement by displaying a sequence of static frames. A movie is a perfect example of frame-based animation; each frame of the film is a frame of animation. When the frames are shown in rapid succession, they create the illusion of movement. In frame-based animation, there is no concept of an object distinguishable from the background; everything is reproduced on each frame. The number of images used in the Count applets in the last chapter would make a good frame-based animation. By treating each image as an animation frame and displaying them all over time, you can create counting animations. Cast-Based Animation

Cast-based animation, which also is called sprite animation, is a very popular form of animation and has seen a lot of usage in games. Cast-based animation involves objects that move independently of the background. At this point, you may be a little confused by the use of the word "object" when referring to parts of an image. In this case, an object is something that logically can be thought of as a separate entity from the background of an image. Each object in a cast-based animation is referred to as a sprite, and can have a changing position. Almost every video game uses sprites to some degree. For example, every object in the classic Asteroids game is a sprite moving independently of the other objects. Sprites generally are assigned a position and a velocity, which determine how they move. Time-Based Animation

A better animation technique for moving elements on a page is a time-based technique that animates the element to the target position within a specified time. This also produces a more consistent animation across different browsers and OSs.

JavaScript Input Controls (Javascript Forms) We get data into a JavaScript program using the prompt() function. This can be easily achieved by including a form in a web page. A form includes several elements, each of which is a button, check box or a small slot for entering text. Furthermore, we can link each of these elements with its own piece of JavaScript code, so that when the element is clicked on, JavaScript does something. This time it is the user, not the program, that decides when data is passed to the program, and in what order. The <FORM> tag 27
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

The <FORM> tag is terminated by </FORM> and contains as much plain text and HTML as one likes (tables, images, hyperlinks etc), However, it also contains input tags, which usually take the form of <INPUT> followed by </INPUT>. Textbox controls in javascript Example 1 <html> <tittle>forms</title> <head> <FORM NAME=myForm> var firstnumber<INPUT TYPE="text"></INPUT><br> var secondnumber<INPUT TYPE="text"></INPUT><br> var total<INPUT TYPE="text"></INPUT><br> <INPUT TYPE="button" VALUE="Click on me!" ONCLICK=alert("the total is: + total);"> </INPUT>

</INPUT> <HR><P> </FORM> </head> </html> Example2 <html> <tittle>forms</title> <head> 28


JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

<FORM NAME=askName> Please enter your name : <INPUT TYPE="text" NAME=person SIZE=40 </INPUT> <BR><CENTER> <INPUT TYPE="button" VALUE="Here it is" ONCLICK="say_hello();"> </INPUT> </CENTER> </FORM>

<SCRIPT LANGUAGE="JavaScript"> function say_hello () { var user = askName.person.value; if (user == "") document.write("Ah ha! I see you are the man with no name!"); else document.write("Welcome, " + user); document.write("<P>"); } </SCRIPT> </head> </html> Radio buttons in javascript They are small circles which the user can click on to set them or clear them. When they are set, they are filled in black. When they are cleared, they are white. To create a radio button, use the <INPUT TYPE="radio"> tag. The caption to the button is displayed as normal text afterwards. 29
JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

Radio buttons are similar to check boxes with one essential difference. You can group several radio buttons together in which case the user will only be able to select one of them at a time. If the user clicks on any of the buttons, then that one becomes set, and any other button that was set is cleared automatically. <html> <title>forms</title> <head> <FORM NAME=quiz> In which country would you find the Great Wall of China? <P> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(1);"></INPUT> England <BR> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(2);"></INPUT> Russia <BR> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(3);"></INPUT> China <BR> <INPUT TYPE="radio" NAME="q" ONCLICK="guess(4);"></INPUT> Australia <P> <INPUT TYPE="button" ONCLICK="markAnswer();" VALUE="Done"></INPUT> </FORM> <HR><P> </FORM> </head> </html> Text areas A text area is similar to a text box, except that it is a large rectangular area on the screen into which the user can type as much text as required. When a text area is defined using the <TEXTAREA> tag, you should specify the number of vertical columns and horizontal text rows. Example1 <TEXTAREA NAME="typed" COLS=30 ROWS=10> Any text that you include in here will appear inside the text area. Most programmers leave this part blank! Of course, the user can change the text in here, otherwise there would be no point! </TEXTAREA

30

JAVASCRIPT TUTORIALS PREPARED BY KABA N. DANIEL

S-ar putea să vă placă și