50
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

Java Script1.1

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Java Script1.1

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

Page 2: Java Script1.1

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.

Page 3: Java Script1.1

Introduction• JavaScript can put dynamic text into an HTML page

– A JavaScript statement like this: – document.write("<h1>" + name + "</h1>") can write a variable text into the display of an HTML page, just like the

static HTML text: <h1>Bill Gates</h1> 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.

Page 4: Java Script1.1

JavaScript How To ...

• Use the <script> tag to insert a JavaScript in an HTML document.• How to Put a JavaScript Into an HTML Document

<html><head> </head> <body> <script type="text/javascript"> document.write("Hello World!") </script> </body> </html>– To insert a script in an HTML document, use the <script> tag.

Use the type attribute to define the scripting language.<script type="text/javascript">

In JavaScript the command for writing some text on a page is document.write: 

document.write("Hello World!")

The script ends: </script>

Page 5: Java Script1.1

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:

<script type="text/javascript"> <!-- some statements //--> </script>

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.

Page 6: Java Script1.1

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. <html> <head> <script type="text/javascript"> some statements </script> </head>

Page 7: Java Script1.1

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.<html> <head> </head> <body> <script type="text/javascript"> some statements </script> </body>

• 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. <html> <head> <script type="text/javascript"> some statements </script> </head> <body> <script type="text/javascript"> some statements </script>

</body>

Page 8: Java Script1.1

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 <script> tag

Now you can call this script, using the "src" attribute, from any of your pages:<html> <head> </head> <body> <script src="xxx.js"></script> </body> </html>

• Remember to place the script exactly where you normally would write the script.

Page 9: Java Script1.1

JavaScript Variables • Variables

A variable is a "container" for information you want to store. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value.

• Rules for Variable names:Variable names are case sensitive They must begin with a letter or the underscore character

• Declare a VariableYou can create a variable with the var statement:var strname = some valueYou can also create a variable without the var statement:strname = some value

• JavaScript Opertators:Same as C ++

Page 10: Java Script1.1

Functions• Functions

A function contains some code that will be executed by an event or a call to that function. A function is a set of statements. You can reuse functions within the same script, or in other documents. You define functions at the beginning of a file (in the head section), and call them later in the document. This is JavaScript's method to alert the user.alert("here goes the message")

• How to Define a FunctionTo create a function you define its name, any values ("arguments"), and some statements:function myfunction(argument1,argument2,etc) { some statements }A function with no arguments must include the parentheses:function myfunction() { some statements }

Page 11: Java Script1.1

• Arguments are variables that will be used in the function. The variable values will be the values passed on by the function call.By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called.Some functions return a value to the calling expressionfunction result(a,b) { c=a+b return c

}• How to Call a Function

A function is not executed before it is called.You can call a function containing arguments:myfunction(argument1,argument2,etc) or without arguments:myfunction()

• The return Statement• Functions that will return a result must use the "return" statement.

This statement specifies the value which will be returned to where the function was called from. Say you have a function that returns the sum of two numbers:

• function total(a,b) { result=a+b return result }

Page 12: Java Script1.1

Conditional & Looping Statements

• Same as C / C ++ / Java

• Conditional StatementsIf StatementSwitch StatementConditional Operator

• Looping Statements for loop do … While loop while loop

Page 13: Java Script1.1

Java Script Rules• JavaScript is Case Sensitive

A function named "myfunction" is not the same as "myFunction". Therefore watch your capitalization when you create or call variables, objects and functions. 

• SymbolsOpen symbols, like  ( { [ " ', must have a matching closing symbol, like  ' " ] } ).

• White SpaceJavaScript ignores extra spaces. You can add white space to your script to make it more readable. These two lines mean exactly the same:

• name="Hege" name = "Hege“Break up a Code Line

You can break up a code line within a text with a backslash. The example below will be displayed properly:document.write("Hello \ World!")

• Note: You can not break up a code line like this:

Page 14: Java Script1.1

Java Script Objects

• String

• Array

• Date

• Math

Page 15: Java Script1.1

JavaScript String Object • The String object is used to work with text.

•The Most Common Methods•length•indexOf()•lastIndexof()•match()•substr()•substring()•toLowerCase()•toUpperCase()

Page 16: Java Script1.1

The Array object • Declaring an Array

You create an instance of the Array object with the "new" keyword.var family_names=new Array(5)The expected number of elements goes inside the parentheses, in this case 5.You assign data to each of the elements in the array like this:family_names[0]="Tove“

family_names[1]="Jani“ family_names[2]="Ståle“ family_names[3]="Hege“ family_names[4]="Kai“• Most Common Methods

length()reverse()slice()sort()

Page 17: Java Script1.1

JavaScript Date Object • The Date object is used to work with dates and times.• You create an instance of the Date object with the "new"

keyword.• To store the current date in a variable called "my_date":

var my_date=new Date()• You can also write a date inside the parentheses of the Date()

object, like this:new Date("Month dd, yyyy hh:mm:ss") new Date("Month dd, yyyy") new Date(yy,mm,dd,hh,mm,ss) new Date(yy,mm,dd) new Date(milliseconds)

• The Most Common Methods– Date() - getFullYear()– getDate() - getHours()– getDay() - getMinutes()– getMonth() - getSeconds()

Page 18: Java Script1.1

JavaScript Math Object

• The built-in Math object includes mathematical constants and functions.

• The built-in Math object includes mathematical constants and functions. You do not need to create the Math object before using it.

• The Most Common Methods– max(x, y)– min(x, y)– random()– round(x)

Page 19: Java Script1.1

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

Page 20: Java Script1.1

ALERT BOX

• <html>• <body>

• <script type="text/javascript">• alert("Hello World!")• </script>

• </body>• </html>

Page 21: Java Script1.1

CONFIRM BOX<html><body>

<script type="text/javascript">var name = confirm("Press a button")if (name == true){document.write("You pressed OK")}else{document.write("You pressed Cancel")}</script>

</body></html>

Page 22: Java Script1.1

PROMPT BOX

<html><head>

</head><body><script type="text/javascript">var name = prompt("Please enter your name","")if (name != null && name != ""){document.write("Hello " + name)}</script>

</body></html>

Page 23: Java Script1.1

Open a new window when clicking on a button

<html><head>

<script language=javascript>function openwindow() {window.open("http://www.qamer.com")}</script>

</head><body><form><input type=button value="Open Window" onclick="openwindow()"></form></body></html>

Page 24: Java Script1.1

Open a new window and control its apearance

<html><head><script type="text/javascript">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")

}</script></head><body><form><input type="button" value="Open Window" onclick="openwindow()"></form></body></html>

Page 25: Java Script1.1

Multiple Windows<html><head><script language=javascript>function openwindow() {window1=window.open("http://www.microsoft.com/")window2=window.open("http://www.qamer.com/")}</script></head><body><form><input type=button value="Open Windows" onclick="openwindow()"></form></body></html>

Page 26: Java Script1.1

Location<html><head><script type="text/javascript">function locate(){location="http://www.qamer.com/"}</script></head><body><form><input type="button" onclick="locate()" value="New location"></form></body></html>

Page 27: Java Script1.1

Refresh<html><head>

<script type="text/javascript">function refresh(){location.reload()}</script></head>

<body><form><input type="button" value="Refresh" onclick="refresh()"></form></body></html>

Page 28: Java Script1.1

Status Bar<html><head><script type="text/javascript">function load(){window.status = "put your message here"}</script></head><body onload="load()"><p>Look in the statusbar</p></body></html>

Page 29: Java Script1.1

Print

<html><head><script type="text/javascript">function printpage(){window.print()}</script>

</head><body><form><input type="button" value="Print this page" onclick="printpage()"></form></body></html>

Page 30: Java Script1.1

• Window– Document– Frame– History– location

Visible Objects

Page 31: Java Script1.1

Java Script Objects HierarchyWindow

Frames Document History Location

TitleAnchor Links Forms

Path Name Protocol Port Host Name

Form[0] Form[1] ...

Element[0] Element[1] Action Method…

Name Value Name Value Selected ...

Page 32: Java Script1.1

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

BrowserDisplay

Mouse & Keyboardaction

Updates to browser display

Mouse & Keyboard events

Page 33: Java Script1.1

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

Page 34: Java Script1.1

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.

Page 35: Java Script1.1

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

Page 36: Java Script1.1

JavaScript Forms • E-mail validation

How you can validate an input-field that contains an e-mail address.• Value validation

How you can validate an input-field with min and max values.• Length validation

How you can validate number of letters in an input-field.• Form validation

A form containing all of the validation above.• Focus

How to set focus on an input field.• Selected

How to make the content in an input field selected.• Radio button

How the client can select options from radio buttons.• Checkbox

How the client can select options from checkboxes.• Select from a dropdown list

How the client can select options from a drop down list.• Select more than one option

How the client can select many options from a drop down list.

Page 37: Java Script1.1

Email Validation<html><head><script type="text/javascript">function validate(){x=document.myFormat=x.myEmail.value.indexOf("@")if (at == -1)

{alert("Not a valid e-mail")return false}

}</script></head>

Page 38: Java Script1.1

<body><form name="myForm" action="tryjs_submitpage.htm"

onsubmit="return validate()">

Enter your E-mail address:<input type="text" name="myEmail">

<input type="submit" value="Send input">

</form></body></html>

Page 39: Java Script1.1

Value Validation<html><head><script type="text/javascript">function validate(){x=document.myFormtxt=x.myInput.valueif (txt>=1 && txt<=5) { return true }else { alert("Must be between 1 and 5") return false } }</script></head><body><form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">Enter a value from 1 to 5:<input type="text" name="myInput"><input type="submit" value="Send input"></form></body></html>

Page 40: Java Script1.1

Length Validation<html> <head><script type="text/javascript">function validate() {x=document.myForminput=x.myInput.valueif (input.length>5) { alert("Do not insert more than 5 characters") return false }else { return true }}</script> </head> <body><form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">In this input box you are not allowed to insert more than 5 characters:<input type="text" name="myInput"><input type="submit" value="Send input"></form></body></html>

Page 41: Java Script1.1

Form Validation<html><head>

<script type="text/javascript">

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<1 || code>5) {

alert("Your code must be between 1 and 5")

submitOK="False"

}

Page 42: Java Script1.1

if (firstname.length>10) { alert("Your name must be less than 10 letters") submitOK="False" }if (submitOK=="False") { return false }}</script></head><body><form name="myForm" action="tryjs_submitpage.htm" onsubmit="return validate()">Enter your e-mail: <input type="text" name="myEmail"> <br>Enter your code, value from 1 to 5: <input type="text" name="myCode"><br>Enter your first name, max 10 letters: <input type="text" name="myName"><br><input type="submit" value="Send input"> </form></body></html>

Page 43: Java Script1.1

Focus<html><head><script type="text/javascript">function setfocus(){document.forms[0].field.focus()}</script></head><body><form><input type="text" name="field" size="30"> <input type="button" value="Get Focus" onclick="setfocus()"> </form></body></html>

Page 44: Java Script1.1

Selected <html><head><script type="text/javascript">function setfocus(){document.forms[0].field.select()document.forms[0].field.focus()}</script></head><body><form><input type="text" name="field" size="30" value="input text"> <input type="button" value="Selected" onclick="setfocus()"> </form></body></html>

Page 45: Java Script1.1

Radio Button

<html><head><script type="text/javascript">function check(browser) {document.forms[0].answer.value=browser}</script></head><body><form>Which browser is your favorite<br><input type="radio"name="browser" onclick="check(this.value)"value="Explorer">Microsoft Internet Explorer<br><input type="radio"name="browser" onclick="check(this.value)"value="Netscape">Netscape Navigator<br><input type="text" name="answer"></form></body></html>

Page 46: Java Script1.1

Check Box<html><head><script type="text/javascript">function check(){coffee=document.forms[0].coffeeanswer=document.forms[0].answertxt=""for (i = 0; i<coffee.length; ++ i){if (coffee[i].checked){txt=txt + coffee[i].value + " "}}answer.value=txt}</script></head>

Page 47: Java Script1.1

<body>

<form>How do you like your coffee<br><input type="checkbox"name="coffee" value="cream">With cream<br>

<input type="checkbox"name="coffee" value="sugar">With sugar<br>

<input type="text" name="answer"><input type="button" name="test" onclick="check()" value="Order"></form>

</body></html>

Page 48: Java Script1.1

Select From the drop down list<html><head><script type="text/javascript"> function put() {option=document.forms[0].dropdown.options[document.forms[0].dropdown.selectedIndex].texttxt=optiondocument.forms[0].favorite.value=txt }</script></head><body><form><p>Select your favorite browser:<select name="dropdown" onchange="put()"><option>Internet Explorer<option>Netscape Navigator</select></p><p>Your favorite browser is:<input type="text"name="favorite" value="Internet Explorer"></p></form></body></html>

Page 49: Java Script1.1

Select more than one option<html><head><script type="text/javascript">function put(){option=document.forms[0].dropdown.options[document.forms[0].dropdown.selectedIn

dex].texttxt=document.forms[0].number.valuetxt=txt + optiondocument.forms[0].number.value=txt}</script></head><body><form>

Page 50: Java Script1.1

Select numbers:<br>

<select name="dropdown">

<option>1

<option>2

<option>3

<option>4

<option>5

<option>6

<option>7

<option>8

<option>9

<option>0

</select>

<input type="button" onclick="put()" value="-->"> <input type="text" name="number">

</form>

</body>

</html>