Java Script
Java Script
Java Script
What is JavaScript?
JavaScript is a Scripting language designed for Web pages.
<script type="text/javascript">
<!–-
and end with
// -->
</script>
JavaScript Example
<html>
<head>
<script type=“text/javascript”>
document.write("Simple javascript");
</script>
</head>
</html>
Methods of Using JavaScript.
1. JavaScripts can reside in a separate page.
2. JavaScript can be embedded in HTML documents -- in the
<head>,or in the <body>
3. JavaScript object attributes can be placed in HTML element
tags.
e.g., <body onLoad="alert('WELCOME')">
1. Using Separate JavaScript Files.
<script src="myjavascript.js”
language="JavaScript”
type="text/javascript">
</script>
2. Embedding JavaScript in HTML.
<a href=”index.html”
onMouseover="document.logo.src='js2.gif'"
onMouseout="document.logo.src='js.gif'">
<img src="js.gif" name="logo">
</a>
Creating an Alert Message
• Alert Box
• Confirm Box
• Prompt Box
Alert Box
<html>
<head>
<script language="javascript">
function disp_alert()
{
alert("Hello again! This is how we" + '\n' +
"add line breaks to an alert box!")
}
</script>
</head>
<body>
<input type="button"
onclick="disp_alert()" value="Display
alert box" />
</body>
</html>
Confirm Box
<html>
<head>
<script language="javascript">
function disp_confirm()
{
var r=confirm("Press a button")
if (r==true)
{
document.write("You pressed OK!")
}
else
{
document.write("You pressed Cancel!")
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_confirm()"
value="Display a confirm box" />
</body>
</html>
Prompt Box
<html>
<head>
<script language="JavaScript">
function disp_prompt()
{
var name=prompt("Please enter your name",”@")
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are
you
today?")
}
}
</script>
</head>
<body>
<input type="button" onclick="disp_prompt()"
value="Display a prompt box">
</body>
</html>
JavaScript Syntax - Variables and
Literals
Variables contain values and use the equal sign to specify
their value.
Variables are created by declaration using the var
command with or without an initial value state.
e.g. var month;
e.g. var month = April;
JavaScript Syntax - Variables and
Literals
•Declaration
– Explicit: var i = 12;
– Implicit: i = 12;
•Variable Scope
– Global
• Declared outside functions
• Any variable implicitly defined
– Local
• Explicit declarations inside functions
JavaScript Syntax - Variables and
Literals
switch (expression)
{
case condition 1: statement(s) break;
case condition 2: statement(s) break;
... case condition n: statement(s) break;
default: statement(s)
}
JavaScript Syntax – Control and
Looping
• A loop is a set of instructions that is executed repeatedly
• The loop uses a counter to track the number of times the command
block has been run
• Loops execute a block of code a specified number of times, or while a
specified condition is true.
this.age=age;
}
Developing More Advanced Scripts
Object Function
Object Functions
history : history object which holds the history of the user’s visit
screen : it will give information about size of user’s display and color depth.
<script type="text/javascript">
document.write(location.search);
</script>
?email=someone@example.com
Navigator Object
The navigator object enables to access general information about the
browser program. – What the browser does and does not support.The
Navigator object is automatically created by the JavaScript runtime
engine and contains information about the client browser.
Properties
appName – returns name of the browser that is processing the script
appVersion – returns version number of the browser
userAgent -The userAgent property supplies the user agent, which is the exact string that
is sent via HTTP as user-agent header when communicating with a web server: browser
Language - Returns the current browser language
cookieEnabled - Returns a Boolean value that specifies whether cookies are enabled in
the browser
cpuClass - Returns the CPU class of the browser's system
onLine - Returns a Boolean value that specifies whether the system is in offline mode
platform - Returns the operating system platform
systemLanguage - Returns the default language used by the OS
userAgent - Returns the value of the user-agent header sent by the client to the server
userLanguage - Returns the OS' natural language setting
Document Object Model (DOM)
Navigator Object
<script type="text/javascript">
</script>
Document Object Model (DOM)
History Object
The History object is automatically created by the JavaScript runtime
engine and consists of an array of URLs.
These URLs are the URLs the user has visited within a browser
window.
The History object is part of the Window object and is accessed
through the window.history property.
history.length – The length property specified how many URLs are
contained in the current history object.
Document Object Model (DOM)
Methods of history object
history.forward() – Loads the next URL in the history list
history.back() - Loads the previous URL in the history list
history.go(URL or no.) - Loads a specific page in the history list
<html>
<body>
<script language=”JavaScript”>
document.write(history.length);
</script>
</body>
</html>
Events
An event is defined as “something that takes place” and that
is exactly what it means in web programming as well.
An event handler is JavaScript code that is designed to run each
time a particular event occurs.
Syntax of handling the events
<Tag Attributes event=“handler”>
Categories of Events
Events fall into four major categories:
User interface events
Mouse events
Key events
HTML events
User interface events happen as controls or other objects on a web
page gain and lose focus.These events are often caused by other user
actions such as a tab key press. They can also happen programmatically
as well.
Mouse events occur when the user moves the mouse or presses one
of the mouse buttons. These events allow a web page to respond to
mouse movements by.
Key events occur when the user presses and/or releases one of the
keyboard keys. Only certain HTML elements can capture keyboard
events.
Finally, there are several events specific to certain HTML elements.
They often relate to the browser window itself or to form controls and
other objects embedded in a web page.
Handle User Interface Events
User interface events deal exclusively with the transfer of
focus from one object inside the web page to another. There
are three user interface events defined in most web
browsers.
Example
<script type="text/javascript" language="javascript">
function upd(instr)
{
document.forms[0].statusbox.value += instr + "; ";
}
</script>
<form action="#">
<input type="text" name="box1“ onblur="upd('blur box1')"><br>
<input type="text" name="box2“ onfocus="upd('focus box2')“
onactivate="upd('activate box2')"><br><br>
Event firing order:
<input type="text" name="statusbox" size="40">
</form>
Handle Mouse Events
JavaScript programs have the ability to track mouse movement and
button clicks as they relate to the web page and controls inside
Example
<script type="text/javascript" language="javascript">
function changeimage(num) {
var img = document.getElementById("SampleImage");
if (num == 1) {
img.src = “img.gif";
} else {
img.src = “flower.gif";
}
}
</script>
<img src=“img.gif"
id="SampleImage"
alt="Sample image"
onmouseover="changeimage(1)"
onmouseout="changeimage(2)" >
Handle Key Events
Like the user interface events, key events fire in a predictable
sequence.There are three main key events in HTML.
Example
<script type="text/javascript" language="javascript">
function upd(instr) {
document.forms[0].statusbox.value += instr + "; ";
}
</script>
<form action="#">
<input type="text" name="box1"
onkeypress="upd('keypress')"
onkeydown="upd('keydown')"
onkeyup="upd('keyup')"><br><br>
Event firing order:
<input type="text" name="statusbox" size="40">
</form>
Handle HTML Events
HTML events means any events that do not belong in the user
interface, mouse, or key event categories.
Some HTML events are triggered directly by a user action,
while others are fired only as an indirect result of a user action.
List of HTML Events
Event handler Applies to:
onAbort Image
onBlur
Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea,
Window
onChange FileUpload, Select, Text, TextArea
onClick Button, Document, Checkbox, Link, Radio, Reset, Submit
onDblClick Document, Link
onDragDrop Window
onError Image, Window
onFocus Button, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea,
Window
onKeyDown Document, Image, Link, TextArea