Download presentation
Presentation is loading. Please wait.
Published byBeverley Lee Modified over 8 years ago
1
Javascript Web Application Development M. Rehan Abbas Ch, UCP, Lahore
2
Introduction JavaScript is a scripting language developed by Netscape. JavaScript works in all major browsers that are version 3.0 or higher. What is JavaScript? JavaScript is a scripting language lightweight programming language used for client Side Scripting A JavaScript can be inserted into an HTML page JavaScript is an open scripting language that anyone can use without purchasing a license. JavaScript is supported by all major browsers like Netscape and Internet Explorer
3
Introduction How Does it Work? When a JavaScript is inserted into an HTML document, the Internet browser will read the HTML and interpret the JavaScript. The JavaScript can be executed immediately, or at a later event. What can a Java Script Do? JavaScript gives HTML designers a programming tool HTML authors are normally not programmers, but since JavaScript is a very light programming language with a very simple syntax, almost anyone can start putting small "snippets" of code into their HTML documents.
4
Introduction JavaScript can put dynamic text into an HTML page A JavaScript statement like this: document.write(" " + name + " ") can write a variable text into the display of an HTML page, just like the static HTML text: Bill Gates does. JavaScript can react to events A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element. JavaScript can read and write HTML elements A JavaScript can read an HTML element and change the content of an HTML element. JavaScript can be used to validate data JavaScripts can be used to validate data in a form before it is submitted to a server. This function is particularly well suited to save the server from extra processing.
5
JavaScript How To... Use the tag to insert a JavaScript in an HTML document. How to Put a JavaScript Into an HTML Document document.write("Hello World!") To insert a script in an HTML document, use the tag. Use the type attribute to define the scripting language. In JavaScript the command for writing some text on a page is document.write: document.write("Hello World!") The script ends:
6
Handle Older Browsers Older browsers that do not support scripts will display the script as page content. To prevent them from doing this, you can use the HTML comment tag: <!-- some statements //--> The two forward slashes in front of the end of comment line (//) are a JavaScript comment symbol, and prevent the JavaScript from trying to compile the line. Note that you can't put // in front of the first comment line (like //<!--), because older browser will display it. Funny? Yes ! But that's the way it is.
7
Java Script Where to… Scripts in a page will be executed immediately when the page loads. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. Where to Put the JavaScript Scripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event. Scripts in the head section: Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it. some statements
8
Java Script Where to… Scripts in the body section: Scripts to be executed when the page loads go in the body section. When you place a script in the body section it generates the content of the page. some statements Scripts in both the body and the head section: You can place an unlimited number of scripts in your document, so you can have scripts in both the body and the head section. some statements
9
How to Run an External JavaScript ? Sometimes you might want to run the same script on several pages, without writing the script on each and every page. To simplify this you can write a script in an external file, and save it with a.js file extension, like this: document.write("This script is external") Save the external file as xxx.js. Note: The external script cannot contain the tag Now you can call this script, using the "src" attribute, from any of your pages: Remember to place the script exactly where you normally would write the script.
10
JavaScript variables are "containers" for storing information: As with algebra, JavaScript variables can be used to hold values (x=5) or expressions (z=x+y). Variable can have short names (like x and y) or more descriptive names (age, sum, totalvolume). Variable names must begin with a letter Variable names can also begin with $ and _ (but we will not use it) Variable names are case sensitive (y and Y are different variables) variables
11
When you assign a text value to a variable, put double or single quotes around the value. When you assign a numeric value to a variable, do not put quotes around the value. If you put quotes around a numeric value, it will be treated as text. var pi=3.14; var person="John Doe"; var answer='Yes I am!'; variables
12
You can declare many variables in one statement. Just start the statement with var and separate the variables by comma: var lastname="Doe", age=30, job="carpenter"; Your declaration can also span multiple lines: var lastname="Doe", age=30, job="carpenter"; Variable declaration
13
JavaScript has dynamic types. This means that the same variable can be used as different types: var x; // Now x is undefined var x = 5; // Now x is a Number var x = "John"; // Now x is a String var x=true; // now x is a boolean var y=false; // now y is a boolean A string can be any text inside quotes. You can use single or double quotes: Example var carname="Volvo XC60"; var carname='Volvo XC60'; JavaScript Data Types
14
The following code creates an Array called cars: var cars=new Array(); cars[0]="Saab"; cars[1]="Volvo"; cars[2]="BMW"; or (condensed array): var cars=new Array("Saab","Volvo","BMW"); or (literal array): Example var cars=["Saab","Volvo","BMW"]; JavaScript Arrays
15
A function is a block of code that will be executed when "someone" calls it: function functionname() { some code to be executed } You can send as many arguments as you like, separated by commas (,) Declare the argument, as variables, when you declare the function: function myFunction(var1,var2) { some code } JavaScript Functions
16
Sometimes you want your function to return a value back to where the call was made. This is possible by using the return statement. Calculate the product of two numbers, and return the result: function myFunction(a,b) { return a*b; } document.getElementById("demo").innerHTML=myFuncti on(4,3); Functions With a Return Value
17
A variable declared (using var) within a JavaScript function becomes LOCAL and can only be accessed from within that function. (the variable has local scope). Variables declared outside a function, become GLOBAL, and all scripts and functions on the web page can access it The lifetime JavaScript variables starts when they are declared. Local variables are deleted when the function is completed. Global variables are deleted when you close the page. Local/Global JavaScript Variables
18
If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable. This statement: carname="Volvo"; will declare the variable carname as a global variable, even if it is executed inside a function. Assigning Values to Undeclared JavaScript Variables
19
= is used to assign values. + is used to add values. * Multiplication, / Division, % Modulus (division remainder), ++ Increment, -- Decrement, x+=y => x=x+y, Example y=5; z=2; x=y+z; The + operator can also be used to add string variables or text values together. txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; Adding two numbers, will return the sum, but adding a number and a string will return a string: z="Hello"+5; JavaScript Operators
20
Comparison operators are used in logical statements to determine equality or difference between variables or values. == equal to, === exactly equal to (equal value and equal type), != not equal, !== not equal (different value or different type), > greater than, = greater than or equal to, <= less than or equal to Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age<18) x="Too young"; Logical operators are used to determine the logic between variables or values && and, || or, ! not JavaScript Comparison and Logical Operators
21
if (time<10) { x="Good morning"; } else if (time<20) { x="Good day"; } else { x="Good evening"; } JavaScript If...Else Statements
22
var day=new Date().getDay(); switch (day) { case 6: x="Today it's Saturday"; break; case 0: x="Today it's Sunday"; break; default: x="Looking forward to the Weekend"; } JavaScript Switch Statement
23
for (var i=0; i "; } Statement 1 is executed before the loop (the code block) starts. Statement 2 defines the condition for running the loop (the code block). Statement 3 is executed each time after the loop (the code block) has been executed. JavaScript For Loop
24
The while loop loops through a block of code as long as a specified condition is true. while (i "; i++; } If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser. JavaScript While Loop
25
This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true do { x=x + "The number is " + i + " "; i++; } while (i<5); The Do/While Loop
26
JavaScript Window Alert box Confirm box Prompt box Open a new window when clicking on a button Open a new window and control its appearance Multiple windows Location Refresh Status bar Print page
27
ALERT BOX alert("Hello World!")
28
CONFIRM BOX var name = confirm("Press a button") if (name == true) { document.write("You pressed OK") } else { document.write("You pressed Cancel") }
29
PROMPT BOX var name = prompt("Please enter your name","") if (name != null && name != "") { document.write("Hello " + name) }
30
Open a new window when clicking on a button function openwindow() { window.open("http://www.google.com") }
31
Open a new window and control its apearance function openwindow() { window.open("http://www.w3schools.com","my_new_window","toolbar=yes,location= yes,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=no,copyhistory =yes,width=400,height=400") } <input type="button" value="Open Window" onclick="openwindow()">
32
Multiple Windows function openwindow() { window1=window.open("http://www.microsoft.com/") window2=window.open("http://www.google.com/") }
33
Location function locate() { location="http://www.google.com/" }
34
Refresh function refresh() { location.reload() }
35
Status Bar function load() { window.status = "put your message here" } Look in the statusbar
36
Print function printpage() { window.print() }
37
Java Script Handles Event Java Script approach to event handling is a two-step process: Defining the events that can be handled by scripts Providing a standard method of connecting these evens to user- supplied JavaScript code. User Browser Java Script Event Handlers Browser Display Mouse & Keyboard action Updates to browser display Mouse & Keyboard events
38
Event Handling Attributes onBlur onChange onClick onDbClick onDragdrop onError onFocus A document,window,frame set,or form element loses focus A text field,text area, or selection is modified and loses the current focus A link,client-side image map area, or form element is clicked A link,client-side image map area, or document is double clicked A dragged object is dropped in a window or frame An error occurs during the loading of an image,window or frame A document,window,frame set or form element receives the current input focus
39
Event Handling Attributes onKeyDown onKeyPress onKeyUP onLoad onMouseDown onMouseMove onMouseOut The user presses a key The user presses and releases a key. The releases a key. An image,document or frame set is loaded. The user presses a mouse button. The user moves the mouse The mouse is moved out of link or an area of a client side image map.
40
Event Handling Attributes onMouseOver onMouseUp onMove onReset onResize onSelect onSubmit onUnload onAbort The mouse is moved over a link. The user releases a mouse button. The user moves a window of frame A user resets a form by clicking on the form’s reset button. The user resizes a window of frame. Text is selected in a text field or text area. A form is submitted The user exits a document or frame set. The Loading of an image is aborted as the result of a user action
41
Email Validation function validate() { x=document.myForm at=x.myEmail.value.indexOf("@") if (at == -1) { alert("Not a valid e-mail") return false }
42
Enter your E-mail address:
43
Value Validation function validate() { x=document.myForm txt=x.myInput.value if (txt>=1 && txt<=5) { return true } else { alert("Must be between 1 and 5") return false } } Enter a value from 1 to 5:
44
Length Validation function validate() { x=document.myForm input=x.myInput.value if (input.length>5) { alert("Do not insert more than 5 characters") return false } else { return true } } In this input box you are not allowed to insert more than 5 characters:
45
Form Validation function validate() { x=document.myForm at=x.myEmail.value.indexOf("@") code=x.myCode.value firstname=x.myName.value submitOK="True" if (at==-1) { alert("Not a valid e-mail") submitOK="False“ } if (code 5) { alert("Your code must be between 1 and 5") submitOK="False" }
46
if (firstname.length>10) { alert("Your name must be less than 10 letters") submitOK="False" } if (submitOK=="False") { return false } } </script > Enter your e-mail: Enter your code, value from 1 to 5: Enter your first name, max 10 letters:
47
Focus function setfocus() { document.forms[0].field.focus() }
48
Selected function setfocus() { document.forms[0].field.select() document.forms[0].field.focus() }
49
Radio Button function check(browser) { document.forms[0].answer.value=browser } Which browser is your favorite <input type="radio" name="browser" onclick="check(this.value)" value="Explorer">Microsoft Internet Explorer <input type="radio" name="browser" onclick="check(this.value)" value="Netscape">Netscape Navigator
50
Check Box function check() { coffee=document.forms[0].coffee answer=document.forms[0].answer txt="" for (i = 0; i<coffee.length; ++ i) { if (coffee[i].checked) { txt=txt + coffee[i].value + " " } answer.value=txt }
51
How do you like your coffee <input type="checkbox" name="coffee" value="cream">With cream <input type="checkbox" name="coffee" value="sugar">With sugar
52
Select From the drop down list function put() { option=document.forms[0].dropdown.options[document.forms[0].dropdown. selectedIndex].text txt=option document.forms[0].favorite.value=txt} Select your favorite browser: Internet Explorer Netscape Navigator Your favorite browser is: <input type="text" name="favorite" value="Internet Explorer">
53
Select more than one option function put() { option=document.forms[0].dropdown.options[document.forms[0].dropdown.select edIndex].text txt=document.forms[0].number.value txt=txt + option document.forms[0].number.value=txt }
54
Select numbers: 1 2 3 4 5 6 7 8 9 0 ">
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.