1 Intro to Javascript
Java script plays an important role in
web development.
It does not require the knowledge of
Java.
Our Agenda:
1. What is Java script?
2. What can Java script do?
3. What makes Java script unique?
What is JavaScript?
2
1. Javascript is interpreted, client side , event
based, object oriented scripting language.
2. Invented in 1995 at Netscape
corporation(livescript).
3. It is case sensitive language.
4. JavaScript is not java.
What can Javascript do?
• It can dynamically modify an HTML page.
(without refreshing the page).
• It can validate user input.
• It can be used to create cookies(stores on
browsers).
• It is a full featured progg language.
What makes Java script
unique?
Support by all major browsers and
enabled by default.
Complex things (like run time
validation of user’s input) are done
simply.
Full integration with HTMl/CSS.
JavaScript frameworks and
Libraries
.Angular React
• jQuery • [Link]
• [Link] • [Link]
• [Link] • Polymer
• Aurelia • [Link]
No need to write the large lines of codes but use the library directly which is
already made so to make the work easier.
Client Side Scripting
5
CS380
Use javascript with html
6
Internal Java script: using SCRIPT tag
Which provides a block to write the
Javascript programs.
<script type=“text/javascript”>
//javaScript code goes here
</script>
External javascript: to use predefined
programs of any js library.
<script src=“[Link]”></script>
Important functions of JS
7
1. alert()
2. Confirm()
3. [Link]()
4. [Link]()
5. Prompt()
alert() : it is used to alert the user that something has
happened.
<script type =“text/javascript”>
alert(“welcome to JS class”);
</script>
welcome to JS class
OK
Important functions of JS
8
confirm() : Opens up a
confirm/cancel dialog and returns
true/false depending on user’s click.
<script type=“text/javascript”>
<script src=“[Link]”>
confirm(“do you want to leave
homepage?”); Do you want to leave homepage ?
</script> OK Cancel
Important functions of JS
9
[Link]() : writes information to the
browser console, good for testing or
debugging purposes.
<script type=“text/javascript”>
[Link](“welcome to javascript”);
</script>
Important functions of Java
10
Script
[Link]() : write directly to the HTML
document(top left corner of browser)
<script type=“text/javascript”>
[Link](“<h1>welcome to
homepage</h1>”);
</script>
Prompt(msg, default) : creates an dialogue for user
input in textbox.
<script type=“text/javascript”> Enter your comments
prompt(“Enter your comments”,”write here”); Write here
</script> OK cancel
Variables
11
Variables are containers which hold reusable data.
It is a basic unit of storage in a program.
The value stored can be changed during program execution.
<html>
<body>
<script type=“text/javascript”>
Var name;
Name=“hello”;
//var name = “hello world”;
//[Link](Name);
Alert(name);
</script>
</body>
</html>
12
A JavaScript variable is simply a name of storage
location. There are two types of variables in
JavaScript : local variable and global variable.
There are some rules while declaring a JavaScript
variable (also known as identifiers).
Name must start with a letter (a to z or A to Z),
underscore( _ ), or dollar( $ ) sign.
After first letter we can use digits (0 to 9), for
example value1.
JavaScript variables are case sensitive, for
example x and X are different variables.
13
<script>
var x = 10;
var y = 20;
var z=x+y;
[Link](z);
</script>
JavaScript local variable
A JavaScript local variable is declared inside block or
function. It is accessible within the function or block
only. For example:
1. <script>
2. function abc() { var x=10; } //local variable
3. </script>
14
JavaScript global variable
A JavaScript global variable is accessible from any function. A
variable i.e. declared outside the function or declared with window
object is known as global variable. For example:
<script>
var data=200;//global variable
function a(){ [Link](data); }
function b(){ [Link](data); }
a();//calling JavaScript function
b();
</script>
Note
1.A variable that is declared inside a function using the var keyword, will have
a local scope.
2.A variable that is declared inside a function without var keyword, will have a
global scope means acts like a global variable.
Document Object Model
[Link] Object
[Link] of document object
[Link] of document object
[Link] of document object
The document object represents the whole html document.
When html document is loaded in the browser, it becomes a
document object. It is the root element that represents the html
document. It has properties and methods. By the help of document
object, we can add dynamic content to our web page.
Methods of document object
Linking to a JavaScript file:
17
script
<script src="filename" type="text/javascript"></script>
HTML
script tag should be placed in HTML
page's head
script code is stored in a separate .js file
JS code can be placed directly in the
HTML file's body or head (like CSS)
but this is bad style (should separate
content, presentation, and behavior
Event-driven programming
18
split breaks apart a string into an array
using a delimiter
can also be used with regular expressions
(seen later)
join merges an array into a single string,
placing a delimiter between them
A JavaScript statement:
19
alert
alert("IE6 detected. Suck-mode enabled.");
JS
a JS command that pops up a dialog box
with a message
CS380
Event-driven programming
20
you are used to programs start with a
main method (or implicit main like in
PHP)
JavaScript programs instead wait for user
actions called events and respond to
them
event-driven programming: writing
programs driven by user events
Let's write a page with a clickable button
that pops up a "Hello, World" window...
CS380
Buttons
21
<button>Click me!</button> HTML
button's text appears inside tag; can
also contain images
To make a responsive button or other UI
control:
1. choose the control (e.g. button) and event
(e.g. mouse 1. click) of interest
2. write a JavaScript function to run when
the event occurs
3. attach the function to the event on the
CS380 control
JavaScript functions
22
function name() {
statement ;
statement ;
...
statement ;
} JS
function myFunction() {
alert("Hello!");
alert("How are you?");
} JS
the above could be the contents of
[Link] linked to our HTML page
statements placed into functions can be
evaluated in response to user events
CS380
Event handlers
23
<element attributes onclick="function();">...
HTML
<button onclick="myFunction();">Click me!</button>
HTML
JavaScript functions can be set as event
handlers
when you interact with the element, the
function will execute
onclick is just one of many event HTML
attributes we'll use
but popping up an alert window is
disruptive and annoying
CS380
Document Object Model
24
(DOM)
most JS code
manipulates elements
on an HTML page
we can examine
elements' state
e.g. see whether a box
is checked
we can change state
e.g. insert some new
text into a div
we can change styles
DOM element objects
25
Accessing elements:
[Link]
26
var name = [Link]("id");
JS
<button onclick="changeText();">Click me!</button>
<span id="output">replace me</span>
<input id="textbox" type="text" />
HTML
function changeText() {
var span = [Link]("output");
var textBox = [Link]("textbox");
[Link] = "red";
}
JS
Accessing elements:
27
[Link]
[Link] returns the
DOM object for an element with a given
id
can change the text inside most
elements by setting the innerHTML
property
can change the text in form controls by
setting the value property
CS380
Changing element style:
28
[Link]
Property or style
Attribute
object
color color
padding padding
background-color backgroundColor
border-top-width borderTopWidth
Font size fontSize
Font famiy fontFamily
CS380
Preetify
29
function changeText() {
//grab or initialize text here
// font styles added by JS:
[Link] = "13pt";
[Link] = "Comic Sans MS";
[Link] = "red"; // or pink?
}
JS
CS380
30 More Javascript Syntax
CS380
Variables
31
var name = expression; JS
var clientName = "Connie Client";
var age = 32;
var weight = 127.4; JS
variables are declared with the var
keyword (case sensitive)
types are not specified, but JS does have
types ("loosely typed")
Number, Boolean, String, Array, Object,
Function, Null, Undefined
can find out a variable's type by calling
typeof
Number type
32
var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);
JS
integers and real numbers are the same
type (no int vs. double)
same operators: + - * / % ++ -- = += -=
*= /= %=
similar precedence to Java
many operators auto-convert types: "2"
* 3 is 6
Comments (same as Java)
33
// single-line comment
/* multi-line comment */
JS
identical to Java's comment syntax
recall: 4 comment syntaxes
HTML: <!-- comment -->
CSS/JS/PHP: /* comment */
Java/JS/PHP: // comment
PHP: # comment
34
CS380
35
CS380
Math object
36
var rand1to10 = [Link]([Link]() * 10 + 1);
var three = [Link]([Link]);
JS
methods: abs, ceil, cos, floor, log,
max, min, pow, random, round, sin,
sqrt, tan
properties: E, PI
Special values: null and
37
undefined
var ned = null;
var benson = 9;
// at this point in the code,
// ned is null
// benson's 9
// caroline is undefined
JS
undefined : has not been declared, does
not exist
null : exists, but was specifically
assigned an empty or null value
Why does JavaScript have both of these?
Logical operators
38
> < >= <= && || ! == != === !==
most logical operators automatically
convert types:
5 < "7" is true
42 == 42.0 is true
"5.0" == 5 is true
=== and !== are strict equality tests;
checks both type and value
"5.0" === 5 is false
if/else statement (same as
39
Java)
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
JS
identical structure to Java's if/else
statement
JavaScript allows almost anything as a
condition
Boolean type
40
var iLike190M = true;
var ieIsGood = "IE6" > 0; // false
if ("web devevelopment is great") { /* true */ }
if (0) { /* false */ }
JS
any value can be used as a Boolean
"falsey" values: 0, 0.0, NaN, "", null, and
undefined
"truthy" values: anything else
converting a value into a Boolean
explicitly:
var boolValue = Boolean(otherValue);
var boolValue = !!(otherValue);
for loop (same as Java)
41
var sum = 0;
for (var i = 0; i < 100; i++) {
sum = sum + i;
}
JS
var s1 = "hello";
var s2 = "";
for (var i = 0; i < [Link]; i++) {
s2 += [Link](i) + [Link](i);
}
// s2 stores "hheelllloo"
JS
CS380
while loops (same as Java)
42
while (condition) {
statements;
} JS
do {
statements;
} while (condition);
JS
break and continue keywords also
behave as in Java
CS380
43
CS380
44
CS380
Popup boxes
45
alert("message"); // message
confirm("message"); // returns true or false
prompt("message"); // returns user input string
JS
CS380
Arrays
46
var name = []; // empty array
var name = [value, value, ..., value]; // pre-filled
name[index] = value; // store element
JS
var ducks = ["Huey", "Dewey", "Louie"];
var stooges = []; // [Link] is 0
stooges[0] = "Larry"; // [Link] is 1
stooges[1] = "Moe"; // [Link] is 2
stooges[4] = "Curly"; // [Link] is 5
stooges[4] = "Shemp"; // [Link] is 5
JS
CS380
Array methods
47
var a = ["Stef", "Jason"]; // Stef, Jason
[Link]("Brian"); // Stef, Jason, Brian
[Link]("Kelly"); // Kelly, Stef, Jason, Brian
[Link](); // Kelly, Stef, Jason
[Link](); // Stef, Jason
[Link](); // Jason, Stef
JS
array serves as many data structures: list,
queue, stack, ...
methods: concat, join, pop, push, reverse,
shift, slice, sort, splice, toString, unshift
push and pop add / remove from back
unshift and shift add / remove from front
shift and pop return the element that is
removed
String type
48
var s = "Connie Client";
var fName = [Link](0, [Link](" ")); // "Connie"
var len = [Link]; // 13
var s2 = 'Melvin Merchant';
JS
methods: charAt, charCodeAt,
fromCharCode, indexOf, lastIndexOf,
replace, split, substring, toLowerCase,
toUpperCase
charAt returns a one-letter String (there is
no char type)
length property (not a method as in Java)
Strings can be specified with "" or ''
More about String
49
escape sequences behave as in Java: \' \"
\& \n \t \\
converting between numbers and
var Strings:
count = 10;
var s1 = "" + count; // "10"
var s2 = count + " bananas, ah ah ah!"; // "10 bananas, ah
ah ah!"
var n1 = parseInt("42 is the answer"); // 42
var n2 = parseFloat("booyah"); // NaN JS
accessing the letters of a String:
var firstLetter = s[0]; // fails in IE
var firstLetter = [Link](0); // does work in IE
var lastLetter = [Link]([Link] - 1);
JS
CS380
Splitting strings: split and
50
join
var s = "the quick brown fox";
var a = [Link](" "); // ["the", "quick", "brown", "fox"]
[Link](); // ["fox", "brown", "quick", "the"]
s = [Link]("!"); // "fox!brown!quick!the"
JS
split breaks apart a string into an array
using a delimiter
can also be used with regular expressions
(seen later)
join merges an array into a single string,
placing a delimiter between them
Practical 7
51
validation an email ID and a phone number as per the
following conditions:Email: Must follow the pattern
name@[Link]
[Link] Validation:
Number: Must contain exactly
10
Thedigits
regular only.
expression
/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-
Z]{2,}$/ ensures the email follows the pattern like
name@[Link].
[Link] Validation:
The regular expression/^\d{10}$/ ensures the phone
number contains exactly 10 digits.
This form checks both the email and phone number when the form is submitted,
and will alert the user if there are validation errors.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Email and Phone Number Validation</title>
<script>
function validateForm() {
var email = [Link]("email").value;
var phone = [Link]("phone").value;
// Email validation regex
var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]
{2,}$/;
// Phone number validation regex (10 digits only)
var phonePattern = /^\d{10}$/;
// Validate Email
if () {
alert("Please enter a valid email address (e.g.,
name@[Link]).");
return false;
// Validate Phone Number
if () {
alert("Please enter a valid 10-digit phone number.");
return false;
}
// If both are valid
alert("Validation successful! Form is ready to submit.");
return true;
}
</script>
</head>
<body>
<h2>Email and Phone Number Validation Form</h2>
<form onsubmit="return validateForm()">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br><br>
<label for="phone">Phone Number:</label><br>
<input type="text" id="phone" name="phone"><br><br>
<input type="submit" value="Submit">
</form>
</body></html>
JavaScript validation for the registration form to include
additional validation for the Name and Password fields:
•Name: Should contain only alphabets, and the length should be
at least 6 characters.
•Password: Should have a minimum length of 6 characters.
<!DOCTYPE html>
<html lang="en"> <head> <meta charset="UTF-8"> <meta
name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registration Form Validation</title>
<script>
function validateForm()
{
var name = [Link]("name").value;
var email = [Link]("email").value;
var phone = [Link]("phone").value;
var password = [Link]("password").value;
// Name validation regex (only alphabets, minimum 6 characters)
var namePattern = /^[A-Za-z]{6,}$/;
// Email validation regex var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-
Z0-9.-]+\.[a-zA-Z]{2,}$/;
// Phone number validation regex (10 digits only)
var phonePattern = /^\d{10}$/;
// Password length validation (minimum 6 characters)
var passwordPattern = /^.{6,}$/;
// Validate Name
if ()
{
alert("Please enter a valid name (alphabets only, and at least 6
characters).");
return false;
}
// Validate Email
if ()
{
alert("Please enter a valid email address (e.g.,
name@[Link]).");
return false;
}
// Validate Phone Number
if ()
{
alert("Please enter a valid 10-digit phone number.");
// Validate Password
if ()
{
alert("Password must be at least 6 characters long.");
return false;
}
// If all validations pass
alert("Validation successful! Form is ready to submit.");
return true;
}
</script>
</head>
<h2>Registration Form with Validation</h2>
<form onsubmit="return validateForm()">
<label for="name">Name:</label><br>
<input type="text" id="name"
name="name"><br><br>
<label for="email">Email:</label><br>
<input type="text" id="email"
name="email"><br><br>
<label for="phone">Phone Number:</label><br>
<input type="text" id="phone"
name="phone"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password"
name="password"><br><br>
<input type="submit" value="Submit">
</form>
Explanation
Name Validation:
The regex ^[A-Za-z]{6,}$
ensures that the name contains only alphabets and is at least 6 characters
long.
If the name doesn’t meet these criteria, an alert is triggered.
Password Validation:
The regex ^.{6,}$
ensures that the password is at least 6 characters long.
If the password is shorter than 6 characters, an alert is triggered.
JavaScript DOM
59
Window
Every element or tags of HTML can be accessed in JavaScript.
They all are converted into objects(document)available in
window when come in javascript
These are javascript code to access
HTML elemnts.
DOM is used when we have to make
changes dynamically in our
webpage.
Like to make the background green,
simply I write on console:
[Link]=“gr
een”;
63 CS380