[go: up one dir, main page]

0% found this document useful (0 votes)
4 views10 pages

java script 22

The document provides an overview of JavaScript, a lightweight, object-based scripting language primarily used for client-side programming. It discusses JavaScript's capabilities, including dynamic text insertion, event handling, and data validation, as well as its integration with HTML through script tags. Additionally, it covers JavaScript objects, coding practices, functions, pop-up boxes, and event handlers, emphasizing the importance of understanding these concepts for effective scripting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

java script 22

The document provides an overview of JavaScript, a lightweight, object-based scripting language primarily used for client-side programming. It discusses JavaScript's capabilities, including dynamic text insertion, event handling, and data validation, as well as its integration with HTML through script tags. Additionally, it covers JavaScript objects, coding practices, functions, pop-up boxes, and event handlers, emphasizing the importance of understanding these concepts for effective scripting.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

10.1.

Introduction
What is JavaScript
This is a scripting language that adds programmatic capabilities on the client
end. It is an Object Based language unlike its counterpart the normal Java
Object oriented language.
It solely employs the use of objects, properties of objects and method in
programming.
Similar to other scripting languages Java Script is light weight. It does not
require a compiler because it is an interpreted language.
JavaScript's may be embedded directly into HTML or linked as an external
file.

Example of Java Script


<HTML>
<body>`
<script type="text/JavaScript">
document.write("This is my first JavaScript!");
</script>
</body> </html>

Executing JavaScript's
Java scripts usually execute in the context of a webpage on a client's
computer.
They require a web browser that is java enabled to interpret java scripts
embedded in the web page. JavaScript's are renown for altering the
appearance of the document, control the display, validate and manipulate
form elements, animation of graphics, storing browsing histories and perform
general computational tasks.
Having learnt JavaScript however its capabilities will only be limited by your
creativity.
The following are some of the capabilities of
• JavaScript gives HTML designers a programming tool
HTML authors are normally not programmers, but JavaScript is a scripting
language with a very simple syntax! Almost anyone can put small "snippets"
of code into their HTML pages.
• 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 an HTML page.
• 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 and change the content of an HTML element.
• JavaScript can be used to validate data
A JavaScript can be used to validate form data before it is submitted to a
server. This saves the server from extra processing.
• JavaScript can be used to detect the visitor's browser
A JavaScript can be used to detect the visitor's browser, and - depending on
the browser load another page specifically designed for that browser.
• JavaScript can be used to create cookies
A JavaScript can be used to store and retrieve information on the visitor's
computer

JAVASCRIPT AN OBJECT BASED LANGUAGE


JavaScript is an Object based scripting (OBS) language. It allows you to
define your own objects and make your own variable types. Similarly it come
with a large number of inbuilt objects for use some of these include the date
object, the string object, the window object e.t.c.
In object oriented theories Objects are entities that have properties and are
associated with a number of methods. For instance a string object may have
a property such as the length.

Consider that example below of such an object


<script type="text/JavaScript">
var txt="Welcome To JavaScript's!";
document.write(txt.length);
</script>

In the following example we are using the length property of the String
object to return the number of characters in a string which in this case is 24
counting all the characters in the string:
Similarly Objects are associated to methods that represent the functions the
object will perform. Consider another example of a script that is making use
of two methods
In the following example we are using the toUpperCase() method of the
String object to display a text in uppercase letters and the write method of
the document to display a web output.
<script type="text/javascript">
varstr="Welcome to JavaScript Programming!"; document.write(st</script>
The output of the code above will be:
WELCOME TO JAVASCRIPT PROGRAMMING!

Embedded Java scripts: JavaScript Placement


To insert a JavaScript into an HTML page, we use the <script> tag. Inside the
<script> tag we use the type attribute to define the scripting language i.e.
<script type="text/JavaScript"> and </script> tells where the Java Script
starts and ends:
Everything between <script> and </script> is processed by the browser as
executable JavaScript statements and data.
You cannot place HTML or XHTML within this tag; it will be agged as an error
by the browser.

Similar to style sheets we can define JavaScript's in the following ways.


• Inline scripts: the script is defined surrounding a portion of content in the
body of the web document.
• Embedded scripts: scripts defined in the head portion of web page.
Usually they are functions to be executed when needed.
• External scripts: scripts defined in a separate file. Use this to centralize
script definitions and provide a larger scope across all pages of a web site.

JavaScripts in a page will be executed immediately while the page loads into
the browser. Sometimes we want to execute a script when a page loads,
other times when a user triggers an event.

Scripts in <head>
Scripts to be executed when triggered, go in the head section.
You can create some form of a trigger in the body section in the form of
controls that when activated will call the scripts in the head. It is common
practice to have functions in this section.
When the page is loaded in memory the script will also load but will not
execute until a trigger initiates it.
<html>
<head>
<script type="text/JavaScript">
function message()
{
alert("This alert box was called with an onload event residing in the head
section as a function message");}
</script>
</head>
<body onload="message()">
</body>
</html>

Scripts in the Body


We can alternatively place the entire JavaScript code in the body section.
The browser in this case will automatically execute all the content of the
script tag without requiring a further trigger.
The script in this particular case will be responsible for the browser content.
<html>
<head>
</head>
<body>
<script type="text/JavaScript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>

JavaScript Objects
Because most of the JavaScript code that you write involves objects,
properties, methods, and event handlers, understanding what these object-
oriented terms mean is essential for folks planning to write their own scripts.
You can think of it this way:
• Objects are always nouns.
• Properties are adjectives.
• Methods are verbs.
• Event handlers are verbs with on tacked to their fronts

The Object Hierarchy


The object hierarchy: this hierarchy applies to the organization of objects
in a document.
Window Object: this appears at the top of the hierarchy representing the
content area of the browser. In multiple frame environments each frame is a
window
The Document Object: each HTML document that gets loaded into a
window becomes a document object. The Document Object contains most of
other kinds of objects in the model
The Form Object: a form is a distinct grouping of content inside HTML ie
everything inside the <form>. . . .</form> element. A document may have
two or more form elements.
Dates and times are not fundamental types. But JavaScript does provide a
type (or class) of object that represents dates and times, and can be used to
manipulate this type of data. A Date object in JavaScript is created with the
new operator and the
Date() constructor:
now = new Date(); // create an object representing the current date and time
xmas = new Date(96, 11, 25); // Create a Date object representing Christmas
Methods of the Date object allow you to get and set the various date and
time values, and to convert the Date to a string, using either local time or
GMT time. For example:
xmas.setYear(xmas.getYear() + 1); // Change the date to next Christmas
document.write("Today is: " + now.toLocaleString());
In addition, the Date object also defines functions (not methods; they are not
invoked through a Date object) to convert a date specified in string or
numeric form to an internal millisecond representation that is useful for
some kinds of date arithmetic.

Java Script Coding


• JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
• Each statement is executed by the browser in the sequence they are
written.
• This example will write a heading and two paragraphs to a web page:
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket {, and ends with a right curly bracket }.
The purpose of a block is to make the sequence of statements execute
together.
This example will write a heading and two paragraphs to a web page:
<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script>

Variables
• JavaScript variables are used to hold values or expressions.
• A variable can have a short name, like x, or a more descriptive name, like
carname.
Rules for JavaScript variable names:
• Variable names are case sensitive (y and Y are two different variables)
• Variable names must begin with a letter or the underscore character
• Note: Because JavaScript is case-sensitive, variable names are case-
sensitive.
• Creating variables in JavaScript is most often referred to as "declaring"
variables.
• You can declare JavaScript variables with the var statement:
var x;
varcarname;
After the declaration shown above, the variables are empty (they have no
values yet).
However, you can also assign values to the variables when you declare
them:
var x=5;
varcarname="Volvo";

Java Script Functions


Similar to other programming a function is a small program that performs
given tasks.
To keep the browser from executing a script when the page loads, you can
put your script into a function.
A function contains code that will be executed by an event or by a call to the
function.
You may call a function from anywhere within a page (or even from other
pages if the function is embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a
document. However, to assure that a function is read/loaded by the browser
before it is called, it could be wise to put functions in the <head> section.
Syntax
functionfunctionname(var1,var2,...,varX)
{
some code
} The parameters var1, var2, etc. are variables or values passed into the
function. The { and the } defines the start and end of the function
<html>
<head>
<script type="text/javascript">
function displaymessage()
{ alert("HelloWorld!");
}
</script>
</head>
<body>
<form>
<input type="button"value="Click me!"onclick="displaymessage/>
</form>
</body>
</html>

Example 2
<html>
<head>
<script type="text/javascript">
function product(a,b)
{ return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
Javascript Pop up Boxes
The hallmark of JavaScript lies in the ability of javascript pop ups

_ Alert Box
• An alert box is often used if you want to make sure information comes
through to the user.
• When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext"); i.e.
<html>
<head>
<script type="text/javascript">
function show alert()
{ alert("I am analertbox!");
}
</script>
</head>
<body>
<input type="button" onclick="show alert()" value="Show
alert box" />
</body>
</html>

Confirm box
• A confirm box is often used if you want the user to verify or accept
something.
• When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.

Syntax
confirm("sometext"); i.e.
<html>
<head>
<script type="text/javascript">
function show confirm()
{
var r=confirm("Press a button");
if (r==true)
{
document.write("You pressed OK!");
}
else f document.write("You pressed Cancel!");
}}
</script>
</head>
<body>
<input type="button"onclick="show confirm()"value="Show confirm box" />
</body>
</html>

_ Prompt box
A prompt box is often used if you want the user to input a value before
entering a page. When a prompt box pops up, the user will have to click
either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.

Syntax
prompt("sometext","defaultvalue");

JavaScript event Handlers


• One of the most important features provided by JavaScript is the ability to
detect and react to events that occur while a document is loading, rendering,
and being browsed by the user. The JavaScript code that handles these
events may be placed within the <script> tag, but more commonly, it is
associated with a specific tag via one or more
special tag attributes.
• For example, you might want to invoke a JavaScript function when the user
passes the mouse over a hyperlink in a document. The JavaScript-aware
browsers support a special "mouse over" event-handler attribute for the <a>
tag called onMouseOver to do just that:

• <a href="doc.html"onMouseOver="status='Click me!'; return true">


• onAbort*
• <img>
• onBlur
• <a><area><body><button><frameset><input><label><s• onChange
• <input><select><textarea>onClickMosttagsonDblClickMostt• <img>
• onFocus
• <a><area><body><button><frameset><input><label><s•
onKeyDownMost tagsonKeyPressMost tags
• onKeyUp-Most tagsonLoad
• <body><frameset><img>*
• onMouseDown- Most tags
• onMouseMove -Most tags
• onMouseOut-Most tags
• onMouseOver-Most tags
• onMouseUp -Most tags
• onReset
• <form>onSelect
• <input><textarea>
• onSubmit
• <form>onUnload
• <body><frameset>

_ The mouse-related events


• The onClick ,onDblClick, onMouseDown and onMouseUp attributes refer to
the mouse button.
• If you need to detect both halves of a mouse click as separate events, use
onMouseDown and onMouseUp. When the user presses the mouse button,
the onMouseDown eventoccurs. The onMouseUp event happens when the
user releases the mouse button.
• The onMouseMove ,onMouseOut, and onMouseOver events happen when
the user drags the mouse pointer. The onMouseOver event occurs when the
mouse first enters the display region occupied by the associated HTML
element.
After entry, onMouseMove events are generated as the mouse moves about
within the element. Finally, when the mouse exits the element, onMouseOut
occurs.
• For some elements, the onFocus event corresponds to onMouseOver, and
onBlur corresponds to onMouseOut.
_ The keyboard events
Only three events currently are supported by the HTML 4 and XHTML
standards relating to user keyboard actions: onKeyDown ,onKeyUp and
onKeyPress,. The onKeyDown event occurs when the user depresses a key
on the keyboard; onKeyUp happens when the key is released. The
onKeyPress attribute is triggered when a key is pressed and released.
Usually, you'll have handlers for either the up and down events, or the
composite keypress event, but not for both.
_ Document events
Most of the document-related event handlers relate to the actions and states
of form controls. For instance, onReset and onSubmit happen when the user
activates the respective reset or submit button. Similarly, onSelect and
onChange occur as users interact with certain form elements. There also are
some document-related event handlers that occur when various document
elements get handled by the browser. For instance, the onLoad event may
happen when a frameset is complete, or when the body of an HTML or
XHTML document gets loaded and displayed by the browser.
Similarly, onUnload occurs when a document is removed from a frame or
window.

Revision Questions
Example _. Write a JavaScript statement to accomplish each of the following
tasks
i. Declare variables sum and x.
ii. Assign 1 to variable x.
iii. Assign 0 to variable sum
iv. Add variable x to variable sum and assign the result to variable sum
v. Print \The sum is" followed by the value of variable sum

Solution:
i. Declare variables sum and x. var x; var sum;
ii. Assign 1 to variable x. x=1 ; or var x = 1;
iii. Assign 0 to variable sum. sum =0 ; or var sum =0;
iv. Add variable x to variable sum and assign the result to variable sum. sum
= xAssignments + sum;
v. Print \The sum is" followed by the value of variable sum.document.write(\
The sum is"+sum);

Exercise 1. _ Giving examples, explain the following terms


Objects
Properties
Methods
Exercise 2. _ Describe the role of JavaScript in HTML
Exercise 3. _ Write a simple script that demonstrates the role stated above
Exercise 4._Highlight any four events that may be captured by JavaScript

You might also like