Вы находитесь на странице: 1из 13

INTRODUCTION to JAVASCRIPT Web documents can be classified into 2 categories: 1.

DYNAMIC WEB PAGES one page can alter its appearance and contents depending on the input conditions and settings that the page was subjected to before loading in the browser. 2. STATIC WEB PAGES are web pages that can only show the same content every time the page is loaded. In other words, if the desire to create a dynamic page arises, the HTML tags will need additional components. There are many components that are available for used depending on the necessity but for now JAVASCRIPT will b used. Javascript was developed by Netscape and now used by several scripting languages as a base script and is supported by almost any browser available today. JAVASCRIPT is a client-side scripting language commonly used to execute commands to aide the webpage to in it execution. Common applications of Javascript are form validation, improvement and dynamic menu selection due to its simplicity. Web design

Advantages of using Javascript It is a simple and light-scripting language. This means that when a page is accessed through the internet, it will not require a lot of resources for the script to run. It can make web pages more reactive to mouse and keyboard events. It can be made to output additional elements in the page whenever necessary. Since the script can output HTML lines you can make additional part of the page show after a certain event is satisfied. How is javascript included in the web document by way of TAGS. The start tag of the script part of the document should be: <script type=text/javascript> </script>

Basic JavaScript Functions 1. How to output plain text into HTML document using Javacript. Command: document.write (String to Write) <html> <head> <title> Using JavaScript </title>

</head> <body> <script type=text/javascript> document.write("This is my First Javascript") </script> </body> </html> 2. How to output HTML lines using JavaScript Command: document.write (string & <tag> contents </tag>) <html> <head> <title> Using JavaScript </title> </head> <body> <script type=text/javascript> document.write("This is my <b> First </b> Javascript") </script> </body> </html> How do we write JavaScript? 1. The use of semicolon (;) as line terminator is Optional. 2. However, if one line should contain multiple lines of code, the line should be separated by a semicolon to denote the end. 3. One line of code can be broken into multiple lines but must b done with care. Strings and other objects should not b broken into several times. <html> <head> <title>uSING jAVASCRIPT</title> <script type= text/javascript> document.write("<b> This line has bold attribute</b><br>") document.write("<i> This line has italics attributes</i><br>") </script> </head> <body> You can also write text and HTML files using Javascript. </body> </html><html> <head> <title>uSING jAVASCRIPT</title> <script type= text/javascript> document.write("<b> This line has bold attribute</b><br>") document.write("<i> This line has italics attributes</i><br>") </script> </head> <body> You can also write text and HTML files using Javascript. </body>

</html>

Output: This line has bold attribute This line has italics attributes You can also write text and HTML files using Javascript.

Where to insert Javascript lines? Though scripts can be inserted almost anywhere. There are two preferred locations of Javascript inside a web page: (1) in the HEAD Section and in the (2) BODY Section. HEAD SECTION scripts located in the head section of the HTML document will only b executed once the function and method names are called upon by an event. EVENTS are actions derived by mouse and keyboard actions or other scripts actions. <html> <head> <title>uSING jAVASCRIPT</title> <script type= text/javascript> function test_f() { document.write("This is was not shown initially. <br>" + "The script rewrote page.") } </script> </head> </body> <h1>Head Section Scripts </h1> <input type="button" onclick="test_f()" value="Press Me"> </body> </html> Functions inside the script need to be loaded first so they need to be read first before their call.

BODY SECTION Scripts in the body section are automatically executed once the page is loaded in the browser. These scripts are usually necessary for the page to load properly. <html> <head> <title>Using Javascript</title> </head> <body>

<h1> Body Section Scripts</h1> <script type= text/javascript> document.write("This line was executed during loading <br><br>") </script> This is another line under the script </body> </html>

HANDS-ON 1. Type in and save the following HTML document <html> <head> <title>USing JavaScript</title> </head> <body>This line is written in HTML <br> <script type=text/javascript> document.write("This line is written in Javascript<br>") </script> This line is also written in HTML </body> </html> When was the javascript executed? Where was the javascript String written?

<html> <head> <title>USing JavaScript</title> <script type=text/javascript> document.write("This line is written in Javascript<br>") </script> </head> <body> This line is written in HTML. <br> This line is also written in HTML. </body> </html> Compare the above code with the code in #1 When was the javascript executed? Where was the javascript String written?

JAVASCRIPT VARIABLES Variable are generally used to temporarily store data. Its value can be changed at any point in the script or after a certain event satisfied. Rules for variable names in JavaScript: Variable names are case sensitive They must begin with letter or the underscore character You cannot use JavaScript reserved words as variable names.

How to declare variables When declaring variable, we use the following syntax: var variable _name(=initialization value) The text inside the () are optional. It is a good practice to initialize all variables before using them into your script, but this is not strictly implemented. It is possible to declare a variable even without the var keyword as well as the initialization value. variable _name(=initialization value) Variables can be declared anywhere in the part of the script before the part of the script that will use it. Lifetime of Variables Variables can only be accessed while the function or method running them is still active. Once the method is done processing, the variable and its value is discarded. Be sure to finish all necessary processing before your functions exit. You cannot retrieve discarded values unless they were stored in another location. Variable inside the function or method are called local variables. Since each method has its own local variable domain, variable names can be reused without having to worry about conflict with other functions which used the same variable name. Variables declared outside of a function are global variables and all the functions can access these variables and change its value. As long as the page is currently active, these variables are accessible.

JavaScript Operators Operators are used to operate on values and or variables. These dictate the changes that are necessary for calculation and logic evaluations. ARITHMETIC OPERATORS OPERATOR DESCRIPTION + Addition Subtraction / Division * Multiplication % Modulus (remainder) -Decrement ++ Increment ASSIGNMENT OPERATORS Operator Equivalent a=x a=x; a=+x a=a+x a-=x a=a-x a/=x a=a/x a*=x a=a*x a%x a=a%x COMPARISON OPERATORS Operator Description == != > < >= <+ Is equal to Is not equal to Is greater than Is less than Is greater than or equal to Is less than or equal to

EXAMPLE a=1; a=a+2 a=1; a=a-2 a=1; a=a/2 a=1; a=a*2 a=1; a=a%2 a=1; a-a=1; a++

VALUE of A 3 -1 0.5 2 1 0 2

Example a=6; a=6; a+=2 a=6; a-=2 a=6; a/=2 a=6; a*=2 a=6; a%=2

Value of A 6 8 4 3 12 0

Expression (a=3) a==3; a !=3 a>3 a<3 a>=3 a<=3

Value of expression True False False True True true

LOGICAL OPERATORS Operator Description

Expression (a=3)

Value of expression

&&

AND (both are true) OR (either/both are true NOT (inverse)

(a==3) && (a!=3) (a==3) =3) !(a!=3) (a !

False True true

STRING CONCATENATION To connect two strings together, we use the + operator. This means that the second string is to be added to the first string. Space should be added in the strings. string1 string2 expression result I am first string1++string2 I am first last! I am string2_string1 I am last! JAVASCRIPT FUNCTIONS Functions are chunks of code that are grouped together to perform an operation. The main objective in using functions is to centralize all common procedures for code reuse and easy maintenance. Example if A,B and C are functions as specified by lines of scripts and 1,2,and 3 are operations that are needed to be done: Without Function Using Functions

A B C
1 3

A B C

A B C
2 3

A ABC
1

B BBA

C CAB
2

On the example on the left side depicts that if a procedure is to do the same operations, lines of code will also be repeated in that process. On the other hand, if functions are used, the reuse of code is possible. Execution of task1 will only call functions A,B, and C respectively. The same is true for task2 and task3. Since the code is reusable, there are less lines of code and less maintenance is required whenever there will be updates on the scripts. Format of a function Functions are located inside the <script> container tags. The following format is usually observed: <script type= text/javascript> Function function_name ([parameter1, parameter1,]) { //lines of code here [return value]

} </script> Function parameters (at the start of the function) and return values (at the end of the function) are optional. Return values are the final output of the function that is to be passed into other components. Function parameters are values that the function will use to process properly. These maybe text, numerical values constants, etc. <html> <head> <title>Using JavaScript</title> <script type="text/javascript"> function test_function () { document.write("this function loaded without a parameter. <br><br>") } function test_func2(time) { alert("Good" + time +". It is nice to meet you!") } </script> </head> <body> <h2> Using Functions</h2> <script type="text/javascript"> test_func1 () </script> <input type="button" onclick="test_func2 ('Morning')" value="morning"> <input type="button" onclick="test_func2 ('Evening')" value="evening"> </body> </html> Functions returning a value <html> <head> <title>Using JavaScript</title> <script type="text/javascript"> function make_return () { document.write("this function returns a integer. <br><br>") return 7 } function alert_me () { num_1 = make_return() alert("There are " + num_1 + "days in a week!") } </script> </head> <body>

<h2> Using return of a functions </h2> <script type=text/javascript> alert_me() </script> </body> </html> Functions that return a value are more useful in breaking down the code into small pieces or modularization. When the functions are modularized, it is convenient to make new functions without having to code a new set of functions. Calling Functions Function calls can occur at almost any point in the HTML code. Some of the functions are called upon after an event is encountered or sometimes, by default. Functions can also call other functions in the process. The following events may trigger the calling of script functions: Windows event onload, onunload Mouse Events onclick, ondblclick, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup Keyboard Events onkeydown, onkeypress, onkeyup Form Elements Events onchange, onsubmit, onreset, onblur, onfocus. How to call a Function A function should be loaded first before it is used. Even if the function is loaded in the memory, it will not execute unless called upon to. You can call a function by specifying its name. If the function requires parameters, there should also be parameters included in the function call. Conditional Statements CS are lines that contain a logical part and an execution path. The logic part resolves what execution path the program, should take. IF STATEMENT this statement executes the block of code when the condition is satisfied (true). <html> <head> <title>Using JavaScript</title> </head> <body> <h2> This is an if statement example </h2> It shows if a random picked number is greater than 50 <br><br> <script type="text/javascript"> var random_num = Math.round (Math.random()*100) document.write(random_num) if (random_num >50) { document.write ("is <b> Greater than </b> 50") } </script> </body>

</html> IF ELSE STATEMENT This statement if you want a default execution if the condition in the if statement failed to be satisfied. <html> <head><title> IF ELSE STATEMENT</title> </head> <body> <script type="text/javascript"> //If the time is less than 10, you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); } </script> </body> </html> NESTED IF ELSE IF ELSE Shorthand Conditional Operator shorthand notation for variable assignments is also implemented in JavaScript. It simply is a shortway of writing a sing ifelse block of code. Syntax: variable_name=(condition) ? value if condition is true: value if consition is false. <html> <head> <title>Using JavaScript</title> <script type="text/javascript"> function getnum() { num1 = prompt ("Enter a number: ","") display_string = (num1%2==0) ?"even!":"Odd!" alert (num1 + "is" + display_string) } </script> </head> <body> <h2> This is a shorthand condition example<h2>

<input type="button" onclick="getnum()"value=" Run"/> </body> </html> SWITCH STATEMENT - is used in place of nested if..else.. if else.. statement. Switch statements are easier to manage and is easier to read. JAVASCRIPT LOOPING LOOPS are commonly used to execute a block of code multiple times. Do while loop is usually applicable when the loop should be executed at least once before evaluating if the loop will go to through the next iteration. While loop is the same as the do while but the evaluation of the iteration is at the beginning of the code block. JAVASCRIPT GUIDELINES Here are few Guidelines to follow when composing your javascript. Javascript is CASE SENSITIVE. When referring to function and variable names, the exact spelling and capitalization should be observed. Reserved words for javascript cannot be used to name variables and functions. Javascript ignores whitespaces Opening and square braces, parenthesis and curly braces should always complement each other. Comments are encouraged. Single line and trailing comments use double forward slashes Block Comments use a container /* and */ For all the comments JAVASCRIPT STRING OBJECT a string is more commonly referred to as text. It contains a collection of different alpha-numeric combinations as well as punctuations/ In javascript, the string data type is used to manage text contents of variables. It contains methods and properties for better manipulation of data. JAVASCRIPT ARRAY OBJECT An array object is a collection of similar data types. They are serialized in order to gain faster access and maintain an organized manipulation. Array items are referred to by their indexes- the relative address of the data in the whole array. In javascript one way to create arrays is by declaring the array name and array size. Another way is to directly specify the contents of the array upon declaration. Ex.
Var titles = new Array (5) Titles {01} = Mr. Titles {02} = Mrs.

Titles {03} = Dr. Titles {04} = Prof. Titles {05} = Engr.

Is the same as
var titles = new array (Mr., Ms., Dr., Prof., Engr.)

JAVASCRIPT DATE OBJECT The date object handles all the date and time functions of the Javascript. This object contains methods to manipulate the Universal Coordinated time which is the time set by the World Time Standard. JAVASCRIPT MATH OBJECT There is a lot of built in math functions and methods in Javascript basically because it was designed to run simple calculations for client-side computing. JAVASCRIPT WINDOW Windows, components of Javascript are commonly used to run verifications, alerts, warnings and even navigate redirect the browser window into other locations. Rather than use an entire page to view errors and warning, it is best to use Javascript for simple purposes like these: ALERTS alerts have the general syntax: Alert (String message to display) - Used to show warnings. It displays a message box that tells the user about the message and waits for the user to confirm the errors message before proceeding with executions. CONFIRM BOXES confirm boxes have general syntax: Confirm(String message to display in the confirm window) - THE CONFIRM WINDOW RETURNS BOOLEAN VALUES DEPENDING ON THE MOUSE ACTION OF THE USER. We can use these values to make dynamic changes on web documents. PROMPT prompts are window that can be used to obtain a single data object. The obtained data is then returns to the function that called the prompt command. Prompts have general syntax: Prompt (String to display in the window, initial value of the field) OPEN NEW WINDOW opening a new window is also possible using Javascripts. The window attributes can also be changed depending on the command that called the window. The general syntax: Window.open (URL of the page to open) REDIRECT TO A NEW LOCATION redirecting a browser to another page is also possible using Javascripts. Redirection is common when website owners need to change their address but still maintain the old url for them to use. Redirect use the following syntax: Location= URL of the page to open.

Вам также может понравиться