Sie sind auf Seite 1von 31

Java Script?

Java script is language developed strictly for the web sites to create interactive web page that can handle calculations, controls such as displaying certain information when certain values provided, validate forms, and more without whole lot of programming effort. In short description, java script is easy programming language specifically designed to make web page elements interactive. An interactive element is one that responds to a user's input. It's developed by NetScape and is not connected to Java but has similarities with C and C++. JavaScript is case sensitive. Like the HTML java script uses open and close tags. Use the following syntax to start and end any java script codes. <script language="javascript"> put your java script statement here </script> <script> - Indicates the document is script language. <language> - Defines the script language, (eg: javascript, vbscript, etc). In this case, language is defined as javascript. </script> - Closes the script tag. // - This is a comment line for java script, which means the computer will not interpret this line as a code. The following is simple java script program displaying a dialog box with the text This is java script dominated page and writes same text on the browser. <html> <head> </head> <body> <script language="javascript"> alert("This is a java script dominated page"); document.write("This is a java script dominated page"); </script> <body> <html> How it works We started this code with the start and close tags: Start <script language="javascript"> Close</script> Then we display a dialog box with this statement: alert("This is a java script dominated page") Alert is a method that displays the string within the brackets. Then we write same message on the browser using this statement: document.write("This is the java script dominated page") Document is an object means this page. Write is a method writes the string in the brackets to the browser.

Java script code can be placed in the head or body section of the html document. The head section is best suited for all your functions and the body section is best for immediate execution code like the one above. Variables are used to store information. A variable's value can change during the script. You could have someone's last name and first name stored in the word name. JavaScript variables are case sensitive so watch upper case and lower case letters when referring to a variable. They also must start with letter or underscore. Declare a variable in JavaScript variable like this: var name;. This means, create variable name. Var is term used to declare a java and JavaScript variables. Assign a value to the variable like this: name="G. Danyeer";. This simply assigns the value G. Danyeer to the variable name. You can declare and assign a value in single statement as follows: var name = "G. Danyeer"; Arrays An array is an indexed list of things called elements or group of related variables. Element value can be whatever you want them to be such as numbers or strings. Array is helpful when ever you want to keep track of a group of related items. Say that we want declare variables for list of cars like this; var car1="Camry"; car2="Corolla"; car3="Accord"; car4="Civic"; car5="Maxima"; The list can go on and on. Here is an array way to do the same. var cars=new Array() car[0]="Camry"; car[1]="Corolla"; car[2]="Accord"; car[3]="Civic"; car[4] ="Maxima"; Note that the first element of array is 0. The variable car now contains list of cars indexed by numbers 0 to 4. What about if we want access the list? We can access the list all at once using loops or individually. Here is how you would write the list on the browser all at once. var x=0; for(x=0;x<4;x++); { cars[x]; document.write(cars[x]); } We declared variable x with initial value of zerro. It's important to initialize variables in

some languages such as c++ but not important for JavaScrip. Then we have loop statement for (x=0;x<4;x++). This loop increments x 0 to 4 and the variable x is place for each index number by assigning x into cars[x]. The document.write statement, writes the value each time that new element is read. The following is a sample of the array explained above. Arrays An array is an indexed list of things called elements or group of related variables. Element value can be whatever you want them to be such as numbers or strings. Array is helpful when ever you want to keep track of a group of related items. Say that we want declare variables for list of cars like this; var car1="Camry"; car2="Corolla"; car3="Accord"; car4="Civic"; car5="Maxima"; The list can go on and on. Here is an array way to do the same. var cars=new Array() car[0]="Camry"; car[1]="Corolla"; car[2]="Accord"; car[3]="Civic"; car[4] ="Maxima"; Note that the first element of array is 0. The variable car now contains list of cars indexed by numbers 0 to 4. What about if we want access the list? We can access the list all at once using loops or individually. Here is how you would write the list on the browser all at once. var x=0; for(x=0;x<4;x++); { cars[x]; document.write(cars[x]); } We declared variable x with initial value of zerro. It's important to initialize variables in some languages such as c++ but not important for JavaScrip. Then we have loop statement for (x=0;x<4;x++). This loop increments x 0 to 4 and the variable x is place for each index number by assigning x into cars[x]. The document.write statement, writes the value each time that new element is read. The following is a sample of the array explained above.

<html> <body> <script language="javascript"> { var cars = new Array() cars[0]="Camry"; cars[1]="Corolla"; cars[2]="Accord"; cars[3]="Civic"; cars[4]="Maxima"; for(x=0;x<=4; x++) { cars[x]; document.write(cars[x]+"<br>"); } } </script> </body> </html>

The result will look like as follows: Camry Corolla Accord Civic Maxima

We can display the result on message box, window or where ever we want. Say that we want display the result on message box when we click on a button. Here is what we would change. Change cars[x] to alert(cars[x]} then remove the java script code from the body and replace with this statement. Put the removed code in the head section within a function called listOfCars(). <input type="button" value="Display the car inventory" name "me" onclick="listOfCars();"> The result would look like this: Like any other languages, java script can be categorized by functions. Function is a collection of java script code that performs an specific task and can be used anywhere in the document by calling it's name. A function can also return a value. The advantage of it, is to avoid repeating codes that does same tasks all over your document. Functions are usually defined in the head of the document and called in the body.

Here is a syntax for none-parameterized function: function functionName() ( java script statement ) Here is a syntax for parameterized function: function functionName(argument1, argument2, etc) ( java script statement ) A function can return a value. Function that returns a value must have a return statement in it. The following function returns the product of two numbers: function product() ( x=2; y=3; z=x*y; return z; ) Functions are not executed before they called. When you calling a function, three things are important.

The name of the function

The number and type of parameters the function expects

What function is supposed to return; for example, a number, a string, or whatever

Functions are usually called from the body section of html document within a java script code. Here is how you would call a none-parameterized function: functionName() And here is how you would call parameterized function: functionName(argument, argument,etc). The following is complete example of none-parameterized function A variable that has a double quoted value is called string variable because the values are kept as they appear. It's integer variables such as X & Y above that can be calculated. Document.write has an object 'document'and a method 'write'. Document defines

characteristics of the overall body of a web page and write method writes the the expression to the specific document object. The function is called from the body. <html> <head> <script language="javascript"> function calculate() { var X = 5; var Y = 4; var Z= X*Y; var xval="X has the value: "; var yval=" Y has the value: "; document.write(""+xval+""+""+X+""+","+""+yval+""+""+Y+""+","+" X*Y is equal "+""+Z+""); } </script> </head> <body> <script language="javascript"> calculate(); </script> </body> </html> The result of the above sample is as follows: X has the value: 5, Y has the value: 4, X*Y is equal 20 The following is complete example of parameterized function: When arguments are passed to a function, their values must be provided when the function is called. This function simply lists the provided values on the page. We passed two arguments; firstName and lastName to the function. Then we write the arguments using document.write statement. The function expects value when it's called. Call without values will display undefined.

<html> <head> <script language="javascript"> function names(firstName,lastName) { document.write (firstName); document.write(lastName); document.write("<br>");

} </script> </head> <body> <script language="javascript"> names("Cilmi"," B."); names("Warsame"," Dool"); names("H."," Faaruuq"); </script> </body> </html> The following is result from this script: Cilmi, B. Warsame, Dool H. Faaruuq The following is complete example of a parameterized function that returns value We passed numOrder and itemPrice to this function. We created a variable called total which is equal to product of the two other numbers. Then we returned the total. We then created another variable called price when the function is called and set it equal to the function name and argument. This variable simply stores returned value from the function. Then we write the variable price using document.write statement. <html> <head> <script language="javascript"> function calculateTotal(numOrdered, itemPrice) { var total=numOrdered*itemPrice; return total; } </script> </head> <body> <script language="javascript"> var price=calculateTotal(4,5.99); document.write("Total: "+price); </script> </body> </html> The result of this script is as follows: Total: 23.96

JavaScript If statment Using if statement, javascript has the ability to make distinctions between different possibilities. For example, you might have a script that checks if Boolean value is true or false, if variable contains number or string value, if an object is empty or populated, or even check type and version of the visitors browser. Here is a syntax for if statement: if (condition) { Action statement } This is a single if statment wich responds on one condition and executes statements inside the curly braces {} when the condition is true. if (condition) { Action statement } else { Alternative action statement } -This executes the statements inside the curly braces when conditon is true and alternative statements when when condition is not true. Notice parenthesis are used around the condition statement. Java scipt if statement uses parenthesis and is case sensitive. Here is an example of if statement. In this example, we created a variable n and initialized with zerro. Then we used if statement to see if n is equal to 0. We display n is zerro if the conditon is true and n is something else if the condition is not true. In this case, the condition is true because n is equal to 0 so the first message is alerted. Notice that == is used for comparison. You cannot use = to compare two values. <html> <body> <script type="text/javascript"> var n=0 if (n==0) { alert("n is zerro") } else { alert("n is some thing else")

} </script> </body> </html> The following is if statement example that checks many conditions in sequence This example is extention of previous example. This time we are using prompt box to get a number from the user. Using if statement, we tested if the provided number is one, two, three, or four alerting the user when a match is found. If the provided number is not within this range, then we check if the number is greater than 4 using > operator. If the condition still false, then we checked if the number is less than 1 using < operator. If none of the conditions are true then else condition is true and it's alert message; You did not enter a number. <html> <body> <script type="text/javascript"> var n=prompt("Enter number between 1 to 4","1") if (n==1) {alert("n is one")} else if(n==2) {alert("n is two")} else if(n==3) {alert("n is three")} else if(n==4) {alert("n is four") } else if(n>4) {alert("You entered number greater than 4, please enter 1-4")} else if(n<1) {alert("You entered number less than 4, please enter 1-4")} else {alert("You did not enter a number!")} </script> </body> </html> Boolean Operators Three boolean operators are used in if statements. The operator, && , allows you to combine two conditions so that both must be true to satisfy the if condition. The operator , ||, which combines two conditions such that the if statement is satisfied if either condition is true. The third boolean operator Operator, !, which makes a condition that returns true, false and vice versa.

Suppose you wanted the previous example to display a message for numbers 1 to 9, 10 to 19, 20 to 29, 30 to 39, and so on. Checking each number would take you hundreds of pages of codes, thanks to the booleans operators. Using boolean operators we can perform the operation in ranges. The following example is modification of previous example using boolean operators: Since the first portion of our alert message is always the same, we created a variable that stores this portion just to make the writing short. We use an if statement to check the provided number in ranges. For example: if (n>=1 && n<10), in order this condition to be true, the number must be 1,2,3,4,5,6,7 , 8 or 9. If the number is 10, the condition will be false because n<10 means 10 is less than 10 but not equal to. If the number is 1, then the condition will be true because n>=1, means n is greater than or equal 1. The operator || is used to check unrelated rang of values and returns true value when one condition is satisfied. For example: if(n<1 || n>100), this condition will return true value when n is less than one, or n is greater than 100 either way. It returns false value, when n is number between 1 and 100 inclusive. The rest of the code is same as previous. <html> <body> <script type="text/javascript"> var n=prompt("Enter a number","1") var enter="You entered a # between" if (n>=1 && n<10) {alert(enter+" 0 and 10")} else if(n>=10 && n<20) {alert(enter+" 9 and 20")} else if(n>=20 && n<30) {alert(enter+" 19 and 30")} else if(n>=30 && n<40) {alert(enter+" 29 and 40")} else if(n>=40 && n<=100) {alert(enter+" 39 and 100")} else if(n<1 || n>100) {alert("You entered a # less than 1 or greater than 100")} else {alert("You did not enter a number!")} </script> </body> </html>

Javascript Case Statements

Javascript case statements can be used to control the different outcomes of a condition. Javascript case statements are recommended when a single condition has a range of outcomes. For example, getDate is a method that can return any day of the week. Javascript case statements can be used to determine and display a message related to the current day. The syntax for javascript case statements are as follows: switch(condition) { case value: action statement } The case value is executed when the condition is "true". If no match is found, then the default condition is executed (if specified). This example uses a javascript case statement to display the current day: Here we declared a variable 'date', and set it to the date object. getDay accesses the days of the week in numbers 1-7. switch sets the condition to test. case tests the value, and executes when it's "true". break is used to "break" the condition. Since the condition is always "true" (hence everyday is a day), there is no need to specify a default statement to execute when there is no match. The example executes when the page is loaded since it's located in the 'body' section of the document. <html> <body> <script type="text/javascript"> <!-var date = newDate() today = date.getDay() switch (today) { case 1: alert("It's Monday") break case 2: alert("It's Tuesday") break case 3: alert("It's Wednesday") break case 4:

alert("It's Thursday") break case 5: alert("It's Friday") break case 6: alert("It's Saturday") break case 7: alert("It's Sunday") break } //--> </script> </body> </html> <body> <script type="text/javascript"> var number = prompt("Enter a number between 1 to 3:", 0) switch (number) { case (number = "1"): alert("You typed" + number); break case (number = "2"): alert("You typed " + number); break case (number = "3"): alert("You typed " + number); break default: alert("Sorry, wrong number"); break } </script> </body>

JavaScript Loops
Loops are set of instructions that repeat elements in specific number of times. Counter variable is used to increment or decrement with each repetition of the loop. The two major groups of loops are, For..Next and Do..Loop. While..Wend is another type of

Do..Loop. The For statements are best used when you want to perform a loop in specific number of times. The Do and While statements are best used to perform a loop an undetermined number of times. For..Loop syntax example. for(i=0;i<value; i++) { javascript statement } This example increments a variable i from 0 to value and continues performing java script statements while i is less then value. <html> <body> <script type="text/javascript"> for (i = 0; i <= 4; i++) { alert("Current value of i is " + i) } </script> </body> </html> This display the value like this on alert boxes: 0,1,2,3,4. The for loop sets i equal to 0 and continues displaying values on an alert boxes as long as i is less than , or equal to, 4. The value of i will increase by 1 each time the loop runs. While..Loop The While..Loop structure repeats a block of statements until a specified condition is met. Bellow is syntax for While..loop: while(variable=value) { javascript statement } The above syntax simply repeats some javascript statements while condition tested false. Bellow is simple example of while loop: <html> <body> <script type="text/javascript"> var x=5*5; x=prompt("What is 5 x 5?"); while (x != 25) {

alert("Wrong answer"); x=prompt("What is 5 x 5?",0); } document.write("Right, the answer is " + x) </script> </body> </html> For this example, we declared variable x and initialized 25. We set it equal to prompt box. The prompt box asks the product of 5x5 and continues asking until true answer is provided. It also informs each wrong attempts or each loop. Bellow is the same example but performs the test at the end of the loop. This time, Do..Loop is used. Using this loop, true value is tested. <html> <body> <script type="text/javascript"> var x = 5*5; do { x=prompt("What is 5 x 5?",0); } while (x != 25) document.write("Right, the answer is " + x) </script> </body> </html> The syntax are same for Do..While and While but keep in mind one tests false condition and the other tests true condtion. The execution of this example will be same as the previous example

Java Script Operators Bellow are list of some of operators available in Java Script. Their meanings and fair example of each. Operator Description Example Result + Addition sign. Adds two numbers 8+2 10 together. Subtraction sign. Subtracts number 8-2 6 from a number. * Multiplication sign. Multiplies two 4*4 16 numbers. / Division sign. Divides a number by 5/2 2.5 another number. % Modulus. Tracks the reminder of 5%2 1 two divided numbers. ++ Increment. Increases values by one x=3 x=4 each run. x++ -Decrement. Decreases values by x=3 x=2 one in each run. x-= Assignment sign. Assigns right x=y x has same value variable or value to the left as y variable. += Left variable is added to right x+=y x=x+y value on each run. -= Left variable is subtracted from x-=y x=x-y right value on each run. *= Left variable is multiplied by the x*=y x=x*y right value on each run. /= Left variable is divided by the right x/=y x=x/y value on each run. %= Reminder is tracked on each run. x%=y x=x%y == Compares two values and returns 4==3 false boolean.td> != Tests if the values are NOT equal 4!=3 true > Test if the left value is greater right 5>4 true value < Test if the left value is less than 5<8 true right value >= Test if left value greater than or 3>=5 false equal to right value

<= &&

||

&&

Test if left value less than or equal to right value Performs a logical conjunction on two expressions. AND for other languages. Performs a logical conjunction on two expressions. OR for other languages. Perform a logical negation on an expression. AND for other languages.

3<=5 See if statement

true See if statement

See if statement

See if statement

See if statement

See if statement

Javascript Form Validation


Javascript form validation means checking that the proper information is entered in the form fields before it is submitted. Forms aren't of much use in terms of processing and posting if you are only limited to HTML, and you don't have access to other scripts such as CGI. This tutaorial is limited to form validations (if you want to learn how to create them, check-out the HTML form page). This example alerts the value entered in the text fields: <html> <head> </head> <body> <FORM name="fm"> Type your first name: <INPUT type="text" name="first"><br> Type your last name: <INPUT type="text" name="last"> <INPUT type="button" name="dis" value="Display" onClick='alert("You say your name is: "+document.fm.first.value+" "+document.fm.last.value)'> </FORM> </body> </html> The only Javascript in this example is onClick. The onClick event handler responds when an object is clicked, and executes the Javascript code or function. In this case, it executes alert box. The alert box displays the values in the text boxes. This example shows how to select and display:

<html> <body> <html> <body> <FORM name="fm2"> Select one: <select name="selec" onchange='alert("You selected "+document.fm2.selec.value)'><br> <option>Select One <option value="Java">Java <option value="C++">C++ <option value="Cobol">Cobol </select> </FORM> </body> </html> </body> </html> We used the onChange event handler to display the alert box with the selected value. onChange executes the specified Javascript code or function in an event change. (when this happens, it executes an alert box that displays the selected value of the select box)

Javascript Object Validations


Javascript object validations have a practical business use (making sure that a required user's information is correct. This example checks and alerts if the fields of the form are empty: <HTML> <HEAD> <script type="text/javascript"> function validate(formCheck) //Function with a parameter representing a form name. { if (formCheck.name.value = "") { alert("Please provide your name:"); formCheck.name.focus(); return false; } var mail = formCheck.email.value if (mail.indexOf("@.") == -1) { alert("Please type a valid email:"); formCheck.email.focus(); return false;

} return true; } </script> </HEAD> <BODY> <FORM name="inform" action="" method="post"> Your Name: <INPUT type=text NAME="name" value="" SIZE=20><br> Your Email: <INPUT type=text NAME="email" value="" SIZE=30><br> <INPUT type="button" name="submit" value="Send" onClick="return validate(inform)";> <INPUT type="reset" name="reset" value="Clear"> </FORM> </BODY> </HTML> How it Works We created a function called validate which takes a parameter. This parameter represents the form name. Using an if statement, we compare the text field name with the empty string. If this field is equal to the empty string, then an alert box is displayed, and the focus is set to this field. We then return a false outcome to avoid the action being continued. The email field is slightly different. For this field, we check if the '@' and '.' are provided. If not, we alert the user, set the focus, and return false. If the two controls pass a "true" value, then the function returns "true". In this case, the onClick event handler returns "true", and nothing happens. Note: if the form action proceeds to another page, use onSubmit instead of onClick. onSubmit executes the function, and continues processing the file defined in the form action.

Javascript Alert Box


A javascript alert box is a dialog box that pops-up with a message and an 'OK' button. The alert method displays an alert box with a string passed to it. For example: alert() will display an empty dialog box with just the 'OK' button. alert("Hello world") will display a dialog box with the message, 'Hello world' and an 'OK' button. (it remains paused until it is clicked). You can display any type of value on an alert box. For example: var number = 12345 alert("The number is: "+number) This simply displays, 'The number is: 12345' on an alert box. The '+' sign ties the two values that are to be displayed in one statement.

Here is a javascript alert box that pops-up when the page is loade <html> <body> <script type="text/javascript"> alert("Hello world") </script> </body> </html> Hello world is displayed in a dialog box when the page is loaded Here is a javascript alert box that pops-up when a link is clicked: <html> <body> <A HREF='javascript:onClick=alert("Not an active link")'>Click here</A> </body> </html> onClick is an event that understands the mouse click. We set the onClick event to the alert box so that when the active link is clicked, the onClick event executes the alert box. Here is a javascript alert box that pops-up when a button is clicked: <html> <body> <form> <input type="button" name="click" value="Click To Alert" onclick='alert("You clicked a button to display an alert box")'> </form> </body> </html> Again, we used the onClick event to display the alert box when the button is clicked

Javascript Prompt Box


The prompt() is a method of the window object, just like alert() we just saw. The format for prompt() is similar to alert(), except for one addition. Prompt uses a text field to enter a value. It also has 'OK' and 'CANCEL' buttons, while the alert has only one button. Here is an example of a prompt box:

prompt("Type your name:"). This prompt method will display the message, 'Type your name' on a prompt box and text field with the default text of undefined. We can display default text in the text field by simply doing the following: prompt("Type your name:", "Type here") The information submitted to the prompt() can be stored in a variable as follows: var name = prompt("Type your name:", "Type here") Once we have a value from the prompt box stored in a variable, we can display it on a message box. Here is a javascript prompt box that displays the provided value on a message box: <html> <body> <script type="text/javascript"> var name = prompt("What is your name?", "Type your name here"); alert("Your name is: "+name) </script> </body> </html> This example displays a prompt box when the page is loaded with the message, 'What is your name?' and the default text field value of, 'Type your name here'. Once a name is provided, it is stored in the variable name, and is displayed on an alert box

Javascript Confirm Box


The Javascript confirm box differs from a regular alert box in that it provides two choices for the user: 'OK' and 'CANCEL' to confirm the request. You can use a variable and an if statement to determine if the 'OK' or 'CANCEL' button is clicked. Here is an example of a confirm box: Confirm: ("Do you want to continue?") This displays a dialog box with the message, 'Do you want to continue?' (with 'OK' and 'CANCEL'). Here is a javascript confirm box that tells you which button you clicked: <html> <body> <script type="text/javascript"> var answer = Confirm: ("Do you want continue?") if (answer) alert("You said: Ok")

else alert("You said: Cancel") </script> </body> </html> We stored the confirm objects in the variable, answer, and then used an if statement to determine which button was clicked. The default and expected button is, 'Ok' so we stated if the answer is equal to 'Ok', then go to a specify location. Else will be "true", and the second message will be displayed, if the current value of answer is not the default value. Here is an example that directs the user to another page when the, 'OK' button is clicked: <html> <body> <script type="text/javascript"> var answer = Confirm: ("Do you want a different page?") if (answer) window.location = "http://www.videogamedeals.com" else alert("Nothing happened") </script> </body> </html> We stored the confirm objects in the variable answer, and then used an if statement to determine which button was clicked. The default and expected button is, 'Ok' so we stated that if the answer is equal to 'Ok', then go to: www.videogamedeals.com. Else will be "true", and the second message, 'Nothing happened' will be displayed if the current value of answer is not the default value.

JavaScript objects Objects are things that are visible. People often describe objects things we can touch, like chair and car but the real meaning of objects in programming are things you see on your screen, like windows, frames, forms, fields, etc. Object could have a Property or Method. Property is an another object within an object. For example, Car is an object, Tire is property of the car when it's party of the car but Tire is another object when it's sitting by it self. Drive is not an object but way of doing. Method is way of doing things like drive. Now, we know what object.property.method are, but how does it apply to javascript?. Look this statement carefully and identify object, property, method: window.document.write()

Window is an object, document is property, and write is method. This is similar to car.tires.drive. If we have just document.write() is object and method similar to tire.spin. We could have object.property without a method. For example, document.formName.textBoxName.value. Document is an object representing whole html page, form is another object, which is the property of document and textBox is another object, which is the property of form. Since we have some idea of what object is, we will discuss different types of objects that are often used in javascript in detail.

String object String is one of stand alone objects that takes string value. For example, var cars = new car("Fox Wagon"). Creates string object containing the value "Fox Wagon". Be carefull because car="Fox Wagon" is not an string object. It's string literal. Java script temporarily converts string literals to string objects so you can use string object methods for string literals too. If you try to evaluate object string using eval function, it will not work because objects do not change in behaviour. Length and Prototype are two string object property available. Length counts the number of characters in the string, for example car.length will return 9 characters long. Prototype creates more properties for the object. Following are list of some string object methods available.
Method Method Decriptions Method Example
var prog="This is is big() example" Big(),Small(),Bold(), Italic(), Returns big, small, bold, italic, strike, document.write(prog.big()) Strike(), sub(), sup() subscript, or superscript text format Result: Returns the position of specified string or -1 if the string is not found. lastIndexOf() start from right to left Displays a Teletype string format. Returns a string in a specified font color or size.

This is is big() example

IndexOf(), lastIndexOf() fixed() fontcolor(), fontsize()

var prog="JavaScript is not hard" var pos=prog.indexOf("h") document.write("found h at: "+pos) Result:

found h at: 18

document.write("This is teletype format".fixed()) var prog="Changes the font color" document.write(prog.fontcolor('blue')) Result:

Changes the font color see

match()

var prog = "Do you see the example" Returns specified value from string or document.write(prog.match("see")) null if the value not found. returns: document.write("chang this to upper case letters".toUpperCase()) Converts strings to upper or lower case

toLowerCase(), toUpperCase()

CHANG THIS TO UPPER CASE LETTERS


returns:

charAt(), charCodeAt()

var prog="What do you see" Returns character at specified position and the other returns unicode document.write(prog.charAt("5")) instead.

returns: d

blink() link() replace()

Returns blinking link. Returns a string as a hyperlink Replaces specified character with

var prog="What do you see" document.write(prog.blink()) returns: What do you see" document.write("This web site".link("http://www.clik.to/program")) returns: This web site document.write("Replace him".replace("him","me"))

specified character. research()

returns:

Replace me 6

substring()

Returns number representing document.write("Character search".search("t")) specified character or -1 if no match returns: found. var prog="Web Programmer/Developer" Returns a string starting specified position and contain specified number document.write(prog.substring(3,14)) of chars. Count starts at 0. returns:

Programmer

Date object The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. It's easy to use the Date object and its methods to work with dates and times in your document. To create a date object, the following syntax is used: dateObjectName = new Date() where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object. The following example explains the use of date object. <html> <body> <script type="text/javascript"> var CDate = new Date() document.write(CDate.getDate()) document.write("/") document.write(CDate.getMonth()+1) document.write("/") document.write(CDate.getFullYear()) document.write("@") document.write(CDate.getHours()+":") document.write(CDate.getMinutes()+":"+CDate.getSeconds()) </script> </body> </html> The variable CDate is set to a date object. Date() returns date object and has methods set(), get() and to (). Set() initializes the date object with the specified value and get() receives date value from the date object. To() converts date object to string Here is the result of this sample: 11/10/2011@15:56:17 <html> <body> <script type="text/javascript"> var CDat = new Date() CDat.setMonth("9")

CDat.setDate("11") document.write(CDat.getDate()+"/"+CDat.getMonth()) </script> </body> </html> This example sets the date to 11 and the month to 9. These value are kept in memory unless you change it. Here is the result 11/9 The following example displays full date, with day name and month name. <html> <body> <script type="text/javascript"> var dat=new Date() var weekday=new Array("Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday","Saturday") var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec") document.write(weekday[dat.getDay()] + " ") document.write(monthname[dat.getMonth()] + " ") document.write(dat.getDate() + ", ") document.write(dat.getFullYear()) </script> </body> </html> In this example, we created two array of objects. One populated with months of the year and the other with days of the week. We can display the date in numbers using date object as we saw before. We can also display the name of the month or the day using the date methods as an index of the array. See array object. Here is the result of this example: Tuesday Oct 11, 2011

The following are list of methods that can be used and description of it's value. Date Object Methods
Method getYear() getFullYear() getMonth() Description Returns the year in ## format. Returns the year #### format. Returns the month of the year in ##.

getDate() getDay() getHours() getMinutes() getSeconds() getTime() getTimezoneOffset() toGMTString() getLocalString() parse("string") UTC(value)

Returns the date in ##. Returns the day in # (0-6). Returns the hour of 24-hr day Returns the minutes of hour Returns the seconds within the minute Returns milliseconds since 1/1/1970. Returns minutes offset from GMT Returns string in universal format Returns string in system's format Returns string to milliseconds Returns date from GMT

Set Method
setYear() setFullYear() setMonth() setDate() setDay() setHours() setMinutes() setSeconds() setTime()

Description
Sets the year in ##. Sets the year in ####. Sets the month of Year in ## Sets the date within the month Sets a day of week in # (0-6) Sets an hour of 24-hr day Sets the minutes of hour Sets the seconds within minute Sets milliseconds since 1970.

Array Object We saw array in the date example above. An array is collection of related data that is contained within a variable. For example: daysOfWeek = new Array ("Sunday", "Monday","Tuesday", "Wednesday", "Thursday","Friday", "Saturday") is an array that stores days of the week. Getting the data out of the array is just as easy. You refer to a particular element of data like this: daysOfWeek[n] where n is the numeric position of the data element starting at 0. For instance daysOfWeek[0] would yield Sunday. See variables & arrays for more array examples.

Javascript Pop-up Window Objects


The javascript pop-up window object refers to the web browser, and all of the items you can see within it. This tutorial will explain how objects are used to create a pop-up window, and the various properties and methods available. Properties are sub-objects which are a part of another object. Methods are the different ways you can do things.

Javascript pop-up window object properties refer to: window name, window size, window address, etc. Javascript pop-up window object methods refer to: open, close, scroll, move, resize, alert, etc. You need to at least specify for a blank window to open. Here is how you open a blank window: window.open() (This will open a blank window, and use all of the default settings). The best way to display a window with a particular: size, color, menu, toolbar, object, etc. is to create a function, and call it when either: a link is clicked, when an object is clicked, or for an onload event. Below is a pop-up window that displays another website in a smaller window: <html> <head> <script type="text/javascript"> function WindowE() { window.open("http://www.videogamedeals.com", "WinE", "width=650,height=500,toolbar=no,resizable=yes") } </script> </head> <body> <a href="javascript:WindowE()">Click Here</a> </body> </html> We created a pop-up window with a width of 650 pixels wide, and a height of 500 pixels high. It displays the website: VideoGameDeals.com. The name of the window is 'WinE', and it is resizable because we set that option to 'yes', however it won't display the toolbar because we set that option to 'no'. This window has been created using a function. When this webpage loads, all you will see is the 'Click Here' link (which calls the function that creates the window) When creating a javascript pop-up window, remember the following syntax: window.open("url", "windowName", "windowAttributes"). URL > specifies the domain name for a website. WindowName > refers to the name of the javascript window object. WindowAttributes > are the various options such as: toolbar, statusbar, scrollbars, etc. Here are a list of attributes for your pop-up window: width height toolbar location directories status

scrollbars

resizable

menubar

Below is a pop-up window that uses all of the various attributes listed above: <html> <head> <script type="text/javascript"> function WindowC() { window.open("http://www.videogamedeals.com", "WinC", "width=550,height=400,toolbar=no,location=no,directories=no,status=no,menubar=no, scrollbars=no,resizable=yes,copyhistory=no") } </script> </head> <body> <form> <input type="button" value="Open Window" onclick="WindowC()"> </form> </body> </html> This pop-up window displays the website: VideoGameDeals.com again, and sets all of the attributes to no (which means that this window will not display any of those named attributes). Also, we are using a button to call the function that creates the window. Below is the result Below is a complete list of Properties and Methods available for javascript pop-up window objects: Property Closed Description Syntax Returns boolean value to determine if window.closed a window has been closed Defines the default message displayed in window.defaultStatus(="message") a window's statusbar Defines the document to be window.document displayed in a window Returns an array window.frames(="frameId") containing references

defaultStatus

document frames

history innerHeight

innerWidth

length

location

locationbar

menubar name opener

outerHeight

outerWidth

pageXOffset

pageYOffset

parent

to all the named child frames in the current window Returns the history window.history list of visited URLs Returns the height of a window's display window.innerHeight = value area Returns the width of a window's display window.innerWidth = value area Returns the number of frames in a window.length window The URL of a website loaded into a window.location window A window's location bar (the property is window.locationbar.visible=false visible) A window's menu bar (the property is window.menubar.visible=false visible) Used to set, or return window.name a window's name The name of a window opened in a window.opener current window Used to return the height of the outer window.outerHeight area of a window Used to return the width of the outer window.outerWidth area of a window Used to return the Xcoordinate of a window.pageXOffset current window Used to return the Ycoordinate of a window.pageYOffset current window The name of a window containing a window.parent particular window

personalbar

scrollbars

self status

statusbar

toolbar

top window Method alert(message) back() blur() captureEvents()

clearTimeout() close() confirm(message)

Returns boolean value indicating the window.personalbar.visible=false visibility of the directories bar Returns boolean value indicating the window.scrollbars.visible=false visibility of the scrollbars bar Used to refer to self.method current window The message displayed in a window.method="message" window's status bar Returns boolean value indicating window.statusbar.visible=false visibility of the status bar Returns boolean value indicating window.toolbar.visible=false visibility of the tool bar Used to return the name of top-most window.top window Used to return the window.[property]or[method] current window Description Syntax Displays a text string alert("Type message here") on a dialog box Loads previous page window.back() in the window Removes the focus window.blur() from a window Sets a window to capture all events of window.captureEvent(eventType) a specified type Clears a timeout (set with the setTimeout window.clearTimeout(timeoutID) method) Used to close a window.close() window Displays a confirm("type message here") confirmation dialog

box with a text message Disables/Enables disableExternalCapture/ window.disableExternalCapture( )/ external event enableExternalCapture window.enableExternalCapture( ) capturing Used to give focus to focus() window.focus() a window Loads the next page forward() window.forward() in a window Invokes the event handleEvent(event) handler for a window.handleEvent(eventID) specified event Moves a window by moveBy(horizontal, the amount specified window.moveBy(HorValue, VerValue) vertical) in the horizontal and vertical directions This method moves the window's left moveTo(x, y) edge and top edge to moveTo(Xposition,Yposition) the specified x and y coordinates Used to open a open() window.open(url, name, attributes) window Displays a print print() window.print() dialog box prompt(message, Displays a prompt window.prompt("Type message here", defaultValue) dialog box value) Release any captured releaseEvents(event) events of a specified window.releaseEvents(eventType) type Resizes a window by resizeBy(horizontal, the specified window.resizeBy(HorValue, VerValue) vertical) horizontal and vertical amounts Resizes a window to resizeTo(width, height) the specified width window.resizeTo(widthValue,heightValue) and height amounts Scrolls the window scroll(x, y) to the specified window.scroll(xValue, yValue) coordinates Scrolls the window's scrollBy(x, y) content area by the window.scrollBy(HorValue, VerValue) specified coordinates

Scrolls the window's content area to the window.scrollTo(xValue, yValue) specified coordinates Evaluates an setInterval(expression, window.setIntervals(expression, expression in time) milliseconds) milliseconds Used to stop a stop() window from window.stop() loading scrollTo(x, y)

Das könnte Ihnen auch gefallen