0% found this document useful (0 votes)
26 views83 pages

L5 Javascript

This document provides an overview of JavaScript, including: - JavaScript is a scripting language used to add interactivity to web pages. It runs in web browsers. - Scripts can be included inline in HTML or externally in .js files. Common uses include form validation, dynamic content, and multimedia elements. - JavaScript code follows basic syntax rules and is case sensitive. It uses camelCase for multi-word variables and functions.

Uploaded by

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

L5 Javascript

This document provides an overview of JavaScript, including: - JavaScript is a scripting language used to add interactivity to web pages. It runs in web browsers. - Scripts can be included inline in HTML or externally in .js files. Common uses include form validation, dynamic content, and multimedia elements. - JavaScript code follows basic syntax rules and is case sensitive. It uses camelCase for multi-word variables and functions.

Uploaded by

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

CUIT 216:

WEB DESIGN AND E-BUSINESS

JAVASCRIPT

1
SCRIPTING LANGUAGES

 Scripting is primarily used to automate tasks e.g. performing calculations


like addition
 Scripting languages are also useful for extracting information from a
database or adding information into a database, thus making the website
dynamic.
 Hence there are server side scripting languages (e.g. PHP) and client-side
scripting languages (e.g. Javascript)
 The four components required to create a fully dynamic web page are a 2

web server (such as Apache), a server-side scripting language (PHP), a


INTRODUCTION TO JAVASCRIPT

3
JAVASCRIPT
 JavaScript is a scripting language produced by Netscape for use
within HTML Web pages.
 JavaScript is loosely based on Java and it is built into all the
major modern browsers.
 An object-oriented computer programming language commonly
used to create interactive effects within web browsers.
 The most common use of JavaScript is to add client-side
behavior to HTML pages, also known as Dynamic HTML 4

(DHTML).
JAVASCRIPT
Scripts are embedded in or included from HTML pages and
interact with the Document Object Model (DOM) of the
page.
One difference between a scripting language and a
programming language is that scripting languages do not
require the compilation step and are rather interpreted.
o For example, normally, a C program needs to be compiled before
running whereas normally, a scripting language like JavaScript or
PHP need not be compiled. 5

o JavaScript is not interpreted


TYPES OF SCRIPTING LANGUAGES

1. Server-side Scripting Language


o Can use huge resources of the server
o Complete all processing in the server and
send plain pages to the client
o Reduces client-side computation overhead
o E.g PHP 6
TYPES OF SCRIPTING LANGUAGES
2. Client-side Scripting Language
o Does not involve server processing
o Complete application is downloaded to the client
browser
o Client browser executes it locally
o Are normally used to add functionality to web pages e.g.
different menu styles, graphic displays or dynamic
advertisements 7

o E.g. JavaScript, VBScript


DIFFERENT SCRIPTING LANGUAGES

3. Active Server Pages (ASP)


oServer side scripting language
oDeveloped by Microsoft
oGood at connecting to Microsoft
databases
oRuns only on Microsoft servers 8
DIFFERENT SCRIPTING LANGUAGES

4. Perl
o Old UNIX language
o Found on all Windows and Linux servers
o Can handle text manipulation tasks
o Excellent web scripting language
o Server side execution 9
DIFFERENT SCRIPTING LANGUAGES
5. PHP (Hypertext Pre-Processor)
o Especially good at connecting to MySQL
o Very popular language
o Runs on UNIX and Windows
o HTML-embedded scripting language
o Syntax looks like C, JAVA, and PERL
o Generates Dynamic content and good User Interface
o Server side execution 10
DIFFERENT SCRIPTING LANGUAGES
6. JSP (Java Server Pages)
o JavaServer Pages (JSP) is a technology for developing web pages
that support dynamic content which helps developers insert java
code in HTML pages by making use of special JSP tags, most of
which start with <% and end with %>.
o Developed by Sun Microsystems
o Uses Java
o similar to PHP and ASP, but it uses the Java programming
language
o Allows you to easily create web content that has both static and 11

dynamic components.
DIFFERENT SCRIPTING LANGUAGES
7. CGI (Common Gateway Interface)
o It offers a standard protocol for web servers to interface with
executable programs running on a server that generate web pages
dynamically.
o Such programs are known as CGI scripts or simply as CGIs; though usually
written in a scripting language, they can be written in any programming
language.
o Needs to launch separate instance of application for each web request.
o CGI is often used to process input information from the user and produce the
12

appropriate output.
DIFFERENT SCRIPTING LANGUAGES

8. VBScript
oMicrosoft’s scripting language
oClient side Scripting language
oVery easy to learn
oIncludes the functionality of Visual Basic 13
DIFFERENT SCRIPTING LANGUAGES

9. JavaScript
o Client-side Scripting language
o Easy to use programming language
o Enhance dynamics and interactive features of a web page
o Allows one to perform calculation, write interactive games,
add special effects, customize graphic selections, create
security passwords 14
QUESTION

State the differences between:


Applet,
Servlet and
Java Server Pages
15
CLIENT-SIDE & SERVER-SIDE TECHNOLOGIES

16
COMMON USES OF JAVASCRIPT
 Used to add multimedia elements
 With JavaScript you can show, hide, change, resize images, and create
image rollovers.
 You can create scrolling text across the status bar.
 Create pages dynamically.
 Based on the user's choices, the date, or other external data, JavaScript
can produce pages that are customized to the user.
 Interact with the user.
 It can do some processing of forms and can validate user input when the
17

user submits the form.


RULES OF JAVASCRIPT PROGRAMMING
JavaScript code is typically embedded in the HTML, to
be interpreted and run by the client's browser.
JavaScript code is case sensitive
White space between words and tabs are ignored
Line breaks are ignored except within a statement
JavaScript statements end with a semi- colon ; 18
RULES OF JAVASCRIPT PROGRAMMING

JavaScript is also a camel-cased language.


o That is, if you're trying to express more than one word
you will eliminate the spaces, leave the first letter
uncapitalized and capitalize the first letter of each
word.
o Thus "get element by id" becomes "getElementByID". 19
RULES OF JAVASCRIPT PROGRAMMING

Because JavaScript ignores spaces, tabs, and newlines that


appear in JavaScript programs, so you are free to format and
indent your code.
Simple statements in JavaScript are generally followed by a
semicolon character, just as they are in C, C++, and Java.
JavaScript, however, allows you to omit this semicolon if your
statements are each placed on a separate line. 20
JAVASCRIPT SYNTAX:
A JavaScript consists of JavaScript statements that are placed
within the <script>... </script> HTML tags in a web page. The
<script> tag alerts the browser program to begin interpreting
all the text between these tags as a script.
So simple syntax of your JavaScript will be as follows:
<script ...>
JavaScript code 21

</script>
JAVASCRIPT SYNTAX:
The script tag takes two important attributes:
Language: This attribute specifies what scripting language
you are using. Typically, its value will be JavaScript. Although
recent versions of HTML (and XHTML, its successor) have
phased out the use of this attribute.
Type: This attribute is what is now recommended to indicate
the scripting language in use and its value should be set to 22

"text/javascript".
JAVASCRIPT SYNTAX:
So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">


//JavaScript code
</script>

OR:

<SCRIPT language = "JavaScript">


//statements 23

</SCRIPT>
IMPLEMENTING JAVASCRIPT

There are different ways to add JavaScript commands


to your Web Pages.
Inline code
External file
24
1. EXTERNAL FILE
Any time you have a block of code which you will want to use on
several different web pages you can place that block in an external
Javascript file.
You can use the SRC attribute of the <SCRIPT> tag to call
JavaScript code from an external text file.
This is useful if you have a lot of code or you want to run it from
several pages, because any number of pages can call the same external
JavaScript file. 25
1. EXTERNAL FILE

Basically everything that would ordinarily go between the


<script> tags can go in your external file.
Note that you can not have the <script> </script> tags
themselves in your external file or you will get errors.
The text file itself contains no HTML tags.
26
EXAMPLE 1:
<!DOCTYPE html>
<html>
<body>
<p>
<script language="javascript" type="text/javascript"
SRC="SourceFile.js">
</script>
</p>
</body> 27
EXAMPLE 1:

SourceFile.js

document.writeln("Hello World");

28
1. EXTERNAL FILE
The biggest advantage to having an external Javascript file is
that once the file has been loaded, the script will hang around
the browser's cache which means if the Javascript is loaded on
one page then it's almost a sure thing that the next page on the
site the user visits will be able to load the file from the
browser's cache instead of having to reload it over the
Internet .
This is an incredibly fast and speedy process.
29
2. IN-LINE JAVASCRIPT

In-line Javascript inserts the contents of external JavaScript


resources directly into the HTML document.
Instead of calling the external Javascript file, in-line Javascript
inserts the actual code (Javascript) into the HTML document
This reduces the number of requests made by a web page by

30
EXTERNAL FILE VS IN-LINE JAVASCRIPT

Including an external file is basically the same as doing an in-line


script, the only difference is that for external file you specify a
filename, and there's no actual code between <script> and
</script>... while for inline script you include the actual code

31
EXAMPLE 2: IN-LINE JAVASCRIPT
<html>
<body>
<script language="javascript" type="text/javascript">

document.write ("Hello World!")

</script>
</body> 32

</html>
COMMENTS IN JAVASCRIPT
JavaScript supports both C-style and C++-style comments, Thus:
Any text between a // and the end of a line is treated as a comment.
Any text between the characters /* and */ is treated as a comment.
This may span multiple lines.
JavaScript also recognizes the HTML comment opening sequence
<!--. JavaScript treats this as a single-line comment, just as it does
the // comment.
The HTML comment closing sequence --> is not recognized by 33

JavaScript so it should be written as //-->


JAVASCRIPT BASICS

34
1. BROWSER OUTPUT
For Javascript there are three ways to communicate
with the user:
a) document.writeln (string) command:
o This can be used while the page is being constructed.
o After the page has finished loading a new
document.writeln (string) command will delete the page in
most browsers, so we use this only while the page is 35

loading.
EXERCISE1:

36
EXERCISE1: OUTPUT

37
1. BROWSER OUTPUT

As the page is loading, Javascript will encounter this


script and it will output "Hello World! " exactly where
the script block appears on the page.
The problem with writeln is that if you use this method
after the page has loaded the browser will destroy the
page and start constructing a new one. 38
1. BROWSER OUTPUT

b) Output(alert)
o The second method is to use a browser alert box.
o While these are incredibly useful for debugging (and
learning the language), they are a horrible way to
communicate with the user because they stop your scripts
from running until the user clicks the OK button. 39
EXERCISE 2:
<p>
This is a test paragraph!!!
</p>
<script type='text/javascript'>
alert('Hello World!');
</script>
<p>
This is test paragraph number 2 40

</p>
EXERCISE 2:

41
1. BROWSER OUTPUT

c) Output (getElementById)
o This is the most powerful and the most complex method.
o Everything on a web page resides in a box.
o You can give each and every box in HTML a unique
identifier (an ID), and Javascript can find boxes you have
labeled and let you manipulate them. 42
EXERCISE 3:

43
1. BROWSER OUTPUT
 The left part of the statement says on this web page
(document) find a block we've named "feedback"
(getElementById ('feedback') ), and change its HTML
(innerHTML) to be 'Hello World!'.
 We can change the contents of 'feedback' at any time, even
after the page has finished loading (which document.writeln
can't do), and without annoying the user with a bunch of 44

pop-up alert boxes (which alert can't do!).


HTML EVENTS
An HTML event can be something the browser does, or something a
user does.
Here are some examples of HTML events:
o An HTML web page has finished loading
o An HTML input field was changed
o An HTML button was clicked
Often, when events happen, you may want to do something.
45

JavaScript lets you execute code when events are detected.


SYNTAX

<some-HTML-element some-event='some JavaScript'>

46
COMMON HTML EVENTS
Events listed on w3schools page are related to the following objects
 Mouse  Print

 Keyboard  Media

 Frame/Object  Animation

 Form  Transition

 Drag  Server-sent

 Clipboard  Misc
 Touch 47

http://www.w3schools.com/jsref/dom_obj_event.asp
EXAMPLE: MOUSE EVENTS

48
2. INPUT
a) Click input

49
2. INPUT
a) Output
o Written text changes after clicking.

50
2. INPUT

b) User Input
o You can add an onClick event to almost any HTML element, but
sometimes you need to be able to ask for input from the user and
process it.
o For that you'll need a basic form element and a button.
o Here we create an input field and give it a name of userInput.
o Then we create a HTML button with an onClick event that will call
51

the function userSubmit().


2. INPUT

o These are all standard HTML form elements but they're not
bound by a <form> tag since we're not going to be submitting
this information to a server.
o Instead, when the user clicks the submit button, the onClick
event will call the userSubmit() function…
52
EXERCISE 5:

53
EXERCISE 5: OUTPUT

54
ONKEYUP EVENT

We don't actually need to have a submit button.


If you'd like to process the user input as the user types then simply
attach an onKeyup event to the input field as such…

<input id='userInput' onKeyUp="userSubmit()" size=60><BR>


<P><div id='result'></div> 55
EXERCISE 5B:

56
EXERCISE 5B: OUTPUT

57
CHANGE THE COLOR OF TEXT WHEN A MOUSE GOES
OVER IT

58
CHANGE THE COLOR OF TEXT WHEN A MOUSE GOES
OVER IT

59
SEARCH FOR AND STATE THE POSITION OF AN
ELEMENT WITHIN A GIVEN SEARCH STRING

<script language="javascript1.1">
var supersetString="
abctopghijklmnopqrstuvwxyzabctopghijklm ";
var subsetString="top";
var lPosition=supersetString.indexOf(subsetString);
alert(lPosition);
60

</script>
ACCESS ELEMENT AT POSITION 5
var str = "abctopghijklmnopqrstuvwxyzabctopghijklm"
alert(str.charAt(5))

61
LOWERCASE THE FIRST CHARACTER
Alert("ABCTOPGHIJKLMNOPQRSTUVWXYZABCTOPGHIJKLM".
charAt(0).toLowerCase() )

62
CHANGE THE BACKGROUND COLOR OF A WEBPAGE WITH ONMOUSEOVER
AND MOUSEOUT EVENTS

63
OUTPUT

64
JAVASCRIPT: LANGUAGE SYNTAX

65
JAVASCRIPT: LANGUAGE SYNTAX

There are three object categories in JavaScript: Native


Objects, Host Objects, and User-Defined Objects.
Native objects: defined by JavaScript.
 String, Number, Array, Image, Date, Math, etc.
Host objects : supplied and always available to JavaScript by the
browser environment.
 window, document, forms, etc.
User-defined objects : defined by the author/programmer 66
COMMON ESCAPE SEQUENCES
Escape sequence Description
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the
current line; do not advance to the next line. Any characters output
after the carriage return overwrite the characters previously output on
that line.
\\ Backslash. Used to represent a backslash character in a string.
\" Double quote. Used to represent a double quote character in a string
contained in double quotes. For example,
window.alert( "\"in quotes\"" );
displays "in quotes" in an alert dialog.

\' Single quote. Used to represent a single quote character in a string. For
example,
window.alert( '\'in quotes\'' ); 67

displays 'in quotes' in an alert dialog.


QUESTION A
Write a javascript program that will display the following
output on the web-page after receiving the maximum number
of asterisk in a row from the user:

*
**
***
**** 68

*****
ARITHMETIC OPERATORS
JavaScript Arithmetic Algebraic JavaScript
operation operator expression expression

Addition + f+7 f + 7

Subtraction - p–c p - c

Multiplication * bm b * m

Division / x/y or x / y

Remainder % r mod s r % s

 Always use parentheses to ensure desired order of evaluation: (a + b) /


69

6
EXERCISE 9:

70
RELATIONAL (INEQUALITY AND EQUALITY)
OPERATORS
Standard algebraic JavaScript equality Sample Meaning of
equality operator or or relational JavaScript JavaScript
relational operator operator condition condition
Equality operators
= == x == y x is equal to y
 != x != y x is not equal to y
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or
equal to y
<= x <= y x is less than or equal
to y
 Note the difference between a relational equality operator “==“ with an
71
EXERCISE 10:

72
VARIABLES AND DATA TYPES
Type of a variable is dynamic: depends on the type of data it contains
JavaScript has six data types:
o Number
o String
o Boolean (values true and false)
o Object
o Null (only value of this type is null)
o Undefined (value of newly created variable) 73

Primitive data types: all but Object


JAVASCRIPT STATEMENTS

Expression statement: any statement that consists entirely of


an expression
o Expression: code that represents a value
Block statement: one or more statements enclosed in { }
braces
Keyword statement: statement beginning with a keyword, e.g.,
var or if 74
JAVASCRIPT STATEMENTS
 var syntax:
 Java-like keyword
statements

75
JAVASCRIPT STATEMENTS

 JavaScript keyword

Statements are very


Similar to Java with
small exceptions

76
JAVASCRIPT OPERATORS
Operators are used to create compound expressions from
simpler expressions
Operators can be classified according to the number of
operands involved:
o Unary: one operand (e.g., typeof i)
• Prefix or postfix (e.g., ++i or i++ )
o Binary: two operands (e.g., x + y) 77

o Ternary: three operands (conditional operator)


JAVASCRIPT OPERATORS:
AUTOMATIC TYPE CONVERSION
Binary operators +, -, *, /, % convert both operands to
Number
o Exception: If one of operands of + is String then the other is
converted to String
Relational operators <, >, <=, >= convert both operands to
Number
o Exception: If both operands are String, no conversion is performed
78

and lexicographic string comparison is performed


JAVASCRIPT OPERATORS:
AUTOMATIC TYPE CONVERSION

Operators ===, !== are strict:


o Two operands are === only if they are of the same type and
have the same value
o “Same value” for objects means that the operands are
references to the same object
Unary +, - convert their operand to Number
Logical &&, ||, ! convert their operands to Boolean 79
JAVASCRIPT FUNCTIONS
Function declaration syntax

80
JAVASCRIPT FUNCTIONS
Function call syntax

81
JAVASCRIPT FUNCTIONS

Number mismatch between argument list and formal


parameter list:
o More arguments: excess ignored
o Fewer arguments: remaining parameters are Undefined

82
QUESTION B
Create a web-page that contains 3 text-boxes and a button.
The user enters values in 2 textboxes, and when he clicks the
command button the result is displayed in the 3rd text box.

83

You might also like