0% found this document useful (0 votes)
0 views43 pages

Lecture 8 - Java Script

This document provides an overview of JavaScript, including its definition, capabilities, and how it interacts with HTML. It covers key concepts such as JavaScript objects, variables, functions, and event handlers, along with examples of pop-up boxes and various coding techniques. The document emphasizes JavaScript's role as a lightweight, object-based scripting language that enhances web pages with dynamic content and interactivity.

Uploaded by

erickchugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views43 pages

Lecture 8 - Java Script

This document provides an overview of JavaScript, including its definition, capabilities, and how it interacts with HTML. It covers key concepts such as JavaScript objects, variables, functions, and event handlers, along with examples of pop-up boxes and various coding techniques. The document emphasizes JavaScript's role as a lightweight, object-based scripting language that enhances web pages with dynamic content and interactivity.

Uploaded by

erickchugu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

LESSON 8

JAVA SCRIPT
Outline
• Introduction
• Executing JavaScript’s
• JavaScript Objects
• Java Script Coding
• Java Variables
• Java Script Functions
• Javascript Pop up Boxes
• JavaScript event Handlers
Introduction
What is Java?
• Java is a popular programming language, created in 1995.
• It is owned by Oracle, and more than 3 billion devices run Java.
• It is used for:
1. Mobile applications (specially Android apps)
2. Desktop applications
3. Web applications
4. Web servers and application servers
5. Games
6. Database connection
7. And much, much more!
Why Use Java
• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• It is one of the most popular programming language in the world
• It is easy to learn and simple to use
• It is open-source and free
• It is secure, fast and powerful
• It has a huge community support (tens of millions of developers)
• Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
• As Java is close to C++ and C#, it makes it easy for programmers to switch
to Java or vice versa
What is Java Script ?
• It 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.
Example of Java Script
• 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.

Note:-
Having learnt JavaScript however its capabilities will only be limited by your
creativity
JavaScript’s Capabilities
The following are some of the capabilities of JavaScript’s extracted from the
w3c website.
1. 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.
2. JavaScript can put dynamic text into an HTML page - A JavaScript state-
ment like this: document.write("<h1>" + name + "</h1>") can write a
variable text into an HTML page.
3. 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’s Capabilities
4. JavaScript can read and write HTML elements - A JavaScript can read
and change the content of an HTML element.
5. 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.
6. 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.
7. 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 bellow 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 to UpperCase() 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">
var str ="Welcome to JavaScript Programming!";
document.write(str.toUpperCase());
</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 flagged as an error by
the browser.
Ways of defining Javascript
Similar to style sheets we can define JavaScript’s in the following ways.
1. Inline scripts: the script is defined surrounding a portion of content
in the body of the web document.
2. Embedded scripts : scripts defined in the head portion of web page.
Usually they are functions to be executed when needed.
3. 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.
Scripts in <head>
• JavaScripts 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 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
Scripts in <head> - Example
<html>
<head>
<script type="text/JavaScript">
function message()
{
alert("This alert box was called with the 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 with-out 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
• This hierarchy applies to the organization of objects in a document.
1. 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
2. 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
3. The Form Object: a form is a distinct grouping of content inside
HTML ie every-thing inside the <form>. . . .</form> element. A
document may have two or more form elements.
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>
Java Script Coding
• 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>
Java Variables
• Variables are containers for storing data values.
• In Java, there are different types of variables, for example:
• String - stores text, such as "Hello". String values are surrounded by double
quotes
• int - stores integers (whole numbers), without decimals, such as 123 or -
123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded
by single quote
• boolean - stores values with two states: true or false
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
car name.
Rules for JavaScript variable names:
1. Variable names are case sensitive (y and Y are two different variables)
2. Variable names must begin with a letter or the underscore character
3. Note: Because JavaScript is case-sensitive, variable names are case-
sensitive.
4. Creating variables in JavaScript is most often referred to as "declaring"
variables.
Variables
• You can declare JavaScript variables with the var statement:
var x;
var carname;
• 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.
Java Script Functions
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("Hello World!");
}
</script>
Java Script Functions
</head>
<body>
<form>
<input type="button" value="Click me!“ onclick="displaymessage()" />
</form>
</body>
</html>
Java Script Functions - 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
1. 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.
Alert box- Syntax
alert("sometext"); i.e.
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>
Javascript Pop up Boxes
2. 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.
Confirm box - 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!");
}
Confirm box - Syntax
else { document.write("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm
box" />
</body>
</html>
Javascript Pop up Boxes
3. 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">
JavaScript event Handlers
• onAbort*
• <img>
• onBlur
• <a><area><body><button><frameset>
• <input><label><select><textarea>
• onChange
• <input><select><textarea>onClickMosttagson
• DblClickMosttagsonError*
• <img>
JavaScript event Handlers
• onFocus
• <a><area><body><button><frameset>
• <input><label><select><textarea>
• 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
JavaScript event Handlers
• <form>onSelect
• <input><textarea>
• onSubmit
• <form>onUnload
• <body><frameset
The mouse-related events
• The onClick ,onDoubleClick, 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 event occurs. 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 ele-ment.
• After entry, onMouseMove events are generated as the mouse moves about
within the element. Finally, when the mouse exits the element, on-MouseOut
occurs.
• For some elements, the onFocus event corresponds to onMouseOver, and on-
Blur corresponds to onMouseOut.
The keyboard events

• Only three events currently are supported by the HTML 4 and XHTML
standards relating to user keyboard actions:
1. The onKeyDown event occurs when the user depresses a key on the
keyboard;
2. onKeyUp happens when the key is released.
3. 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.
Task
Write a JavaScript statement to accomplish each of the following tasks
• Declare variables sum and x.
• Assign 1 to variable x.
• Assign 0 to variable sum
• Add variable x to variable sum and assign the result to variable sum 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);
Revision Questions
1. Giving examples, explain the following terms
• Objects
• Properties
• Methods
2. Describe the role of JavaScript in HTML
3. Write a simple script that demonstrates the role stated above
4. Highlight any four events that may be captured by JavaScript

You might also like