Unit 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 114

CACS 205: Script Language

PREPARED BY KRISHNA PD. ACHARYA


(ME-CHI MULTIPLE CAMPUS)

Java Script
JavaScript is used to create client-side dynamic web pages.
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code for the web browser.
JavaScript is a compact, object-based scripting language for developing client Internet applications.
JavaScript was designed to add interactivity to HTML pages.
A JavaScript is lines of executable computer code.
A JavaScript is usually embedded directly in HTML pages
JavaScript is an Interpreted language (means that scripts execute without preliminary compilation).
Everyone can use JavaScript without purchasing a license.
All major browsers, like Netscape and Internet Explorer, support JavaScript.
JavaScript was developed by Netscape as Live Script - changed to JavaScript when endorsed by Sun
micro system 1993, version 1.0 released with Netscape 2.0.
JavaScript is a powerful scripting language that is also capable of performing extensive form data
collecting and form processing functions.

Java Script
JavaScript / ECMAScript
JavaScript was developed for Netscape. Netscape 2 was the first browser to run JavaScript.
After Netscape the Mozilla foundation continued to develop JavaScript for the Firefox
browser.
The latest JavaScript version was 1.8.5. (Identical to ECMAScript 5).
ECMAScript was developed by ECMA International after the organization adopted
JavaScript.
The first edition ofECMAScript was released in 1997.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in
1997.
ECMAScript is the official name of the language.
From 2015 ECMAScript is named by year (ECMAScript 2015).
ECMAScript is often abbreviated to ES.
ECMAScript 3 is fully supported in all browsers.
ECMAScript 5 is fully supported in all modern browsers.
of Java Script
Advantages
Cross Browser supporting:

This means that the JavaScript codes are supported by various browsers like
Internet Explorer, Netscape Navigator, Mozilla etc. Platform Independent:
JavaScript codes can be executed in any platform like Linux, Microsoft Windows and many
other operating systems.
Lightweight for fast downloading:
The JavaScript codes runs directly in the client machine. The code should be downloaded all
the way from server to the client and this time duration is very minimum and the executing
the codes of JavaScript is also very fast. Validating Data:
of Java Script
The data can be validated in the two different way:
Validating in server side or 111 sewer machine.
Validating in client side or in client machine.
In this two different types of validation of data the second one is much more faster, and
this is done through JavaScript.

Advantages
Sophisticated User Interfaces:
By using JavaScript you can create a user interactive interfaces that can
communicate with the user and the Browser.
In-Built software:
of Java Script
To you don't need any extra tools to write JavaScript, any plain text or HTML editor will
do, so there's no expensive development software to buy. Easy to Learn:
The JavaScript programmer should know the minimal syntax of JavaScript since it supports
many syntax and data types as C and C++.
It's also an easy language to learn, and there's a thriving and supportive online community of
JavaScript developers and information resources.
Designed for programming User-Events: JavaScript supports Object/Event based
programming. So the code written in JavaScript can easily be break down into sub-
modules.

Disadvantages
Launching an application on the client computer.
of Java Script
JavaScript is not used to create stand-alone application; it is only used to add some functionality in any web page.
Reading or writing files:
JavaScript cannot read and write files into the client machines. It can only be used as a utility language to develop any web
site.
Retrieving the text contents of HTML pages or filesfrom the server. Reading
and Writing files to the server:
JavaScript can read and write to any file in the sewer as well.
'h Sending secret e-mails from Web site visitors to you:
JavaScript cannot be used to send email to the visitors or user of the web site. This can be done only with the server side
scripting.
Cannot create Database Application:
By using JavaScript you cannot connect the web site to the database. For this you need to use server-side scripting.
Browser Compatibility Issues:
Not all browsers support the JavaScript codes. The browser may support JavaScript as a whole, but may not support the
codes or lines of codes in JavaScript and may interpret differently.
JavaScript does not implement multiprocessing or multithreading.
of Java Script
Use printers or other devices on the user's system or the client-side LAN.
JavaScript has limitations ofwriting in a client machine. It can only write the cookie in client machine that is also of a
cefiain size i.e. 4K.

Application
JavaScript is used to create interactive websites. It is mainly used for:
Client-side validation,
Dynamic drop-down
menus,
Displaying date and time,
Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box), Displaying clocks etc.
of Java Script
Provide event of based on user action to design CSS and HTML.
JavaScript can update and change both HTML and CSS
JavaScript can calculate, manipulate and validate data
What it does?
JavaScript Can Change HTML Content
JavaScript Can Change HTML Attribute Values
JavaScript Can Change HTML Styles CSS)
JavaScript Can Hide HTML Elements
JavaScript Can Show HTML Elements
Com arision •ava and Java Scri t
JavaScript Java
JavaScript is a small, lightweight programming Java is a full-blown powerful, sophisticated
language. programming language.
Developed by Netscape communications. Developed by Sun Microsystems.
Scripting language interpreted at runtime. True programming compiled to byte-code.
Object-based, has limited numberof built-in Object-oriented, can create their own classes.
objects.
Not fully extensible. Fully extensible
Code integrated with, and embedded in Applies distinct from HTML (accessed from
HTML. HTML pages).
Variables type must not be declared. Variables type must be declared.
Coding Conventions
JavaScript source code can be viewed by Your Java source is hidden because it's only
everybody using "view source command' the compiled byte-code, which the browser
uses, but this is not a guarantee of security.
Coding conventions are style guidelines for programming. Coding conventions can be documented niles for teams to
follow, or just be your individual coding practice. They typically include:
Naming and declaration mles for variables and functions.
'h Rules for the use of white space, indentation, and comments.
Programming practices and principles
Coding conventions secure quality: Ñv7hic11 may include improves code readability and make code maintenance easier.
Naming Conventions
Always use the same namingconvention for all your code. For example:
'h Variable and function names written as camelCase
Global variables written in UPPERCASE (We don't, but it's quite common)
Constants (like PI) written in UPPERCASE
Should you use hyp-hens, camelCase, or under scores in variable names. Hyphens
in HTML and CSS:
HTML5 attributes can stmt with data- (data-quantity, data-price).
Coding Conventions
CSS uses hyphens in property-names (font-size).
Hyphens are not allowed in JavaScript names.
Underscores:
Many programmers prefer to use underscores (date of bilth), especially in SQL databases.
Underscores are often used in PHP documentation.
File Extensions
HTML files should have a.html extension
(not .htm). CSS files should have a .css
extension.
'h JavaScript files should have a .js extension.
Use Lower Case File Names
Most web sewers (Apache, Unix) are casesensitive about file names:
london.jpg cannot be accessed as London.jpg.
Other web servers (Microsoft, IIS) are not case sensitive:
london.jpg can be accessed as London.jpg or london.jpg.
If you use a mix of upper and lower case, you have to be extremely consistent.
If you move from a case insensitive, toa case sensitive sewer, even small errors can break your web site.
To avoid these problems, always use lower case file names (if possible).
Coding Conventions
Performance
Coding conventions are not used by computers. Most rules have little impact on the execution of programs.
Indentation and extra spaces are not significant in small scripts.
For code in development, readability should be preferred. Larger production scripts should be minified.
Coding Conventions
Script Best Practices:
Avoid global variables, avoid new, avoid avoid
Avoid Global Variables
Minimize the use of global variables.
This includes all data types, objects, and functions.
Global variables and functions can be overwritten by other scripts.
Always Declare Local Variables
All variables used in a function should be declared as local variables.
Local variables must be declared with the var keyword or the let keyword, otherwise they will become global variables.
Strict mode does not allow undeclared variables:
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function. This will:
Give cleaner code
Provide a single place to look for local variables
Make it easier to avoid unwanted (implied) global variables
Reduce the possibility of unwanted re-declarations.
By default, JavaScript moves all declarations to the top.
Initialize Variables
It is a good coding practice to initialize variables when you declare them. This will:
Give cleaner code
Provide a single place to initialize variables
Avoid undefined values

JavaScript Comments
'h JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
Single Line Comments
Single line comments stmt with //.
Any text between // and the end of the line will be ignOred by JavaScript (will not be executed).
// Change heading:
// heading 111 has the id tl
").innerHTML = "My First Page";
Multi-line Comments
Multi-line comments stmt with /* and end with
Any text between/* and F/ will be ignored by JavaScript.
The code below will change the
heading with id = "myH" and the
paragraph with id = "myP" in my
web page:

document.getElementById("tl .innerHTML "My First Page";

<noscript> tag in java Script


The <noscript> tag defines an alternate content for users that have disabled scripts in their browser or have a browser that
doesn't support script.
The <noscript> element can be used in both <head> and
When used inside the <head> element: contain only <link>, <style>, and <meta> elements.
The content inside the <noscript> element will be displayed if scripts are not supported, or are disabled in the user's
browser.
It is also a good practice to use the comment tag to "hide" scripts from browsers without support for client-side scripts (so
they don't show them as plain text): <script>

function displayMsg() {
World!
</script>
in
Embedding script html
'h In HTML, JavaScript code must be inseltedbetween<script> and </script> tags.

HTML.

</scripty

Placing scripts at the bottom of the element improves the display speed, because script
interpretation slows down the display.
in
External JavaScript
External scripts are practical when the same code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a
<script> tag: <script

Embedding script html


You can place an external script reference in <head> or as you like. The script
will behave as if it was located exactly where the <script> tag is located. External
scripts cannot contain <script> tags. External JavaScript
Advantages It separates HTML and code.
It makes HTML and JavaScript easier to read and maintain.
Cached JavaScript files can speed up page loads.
We can add several script files to one page - use several script tags: Example -

<script
ascriptExternal References
Operators in JavaScript
Extemal scripts can be referenced with a full URL or with a path relative to the current web page.
<script src="https://www.mechicampus.eud.np/js/myScriptl.js"></script>
JavaScript operators are used to assign values, compare value¾ perfonn arithmetic operations, and more.
1. JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y = 5, the table below
explains the arithmetic operators:
Operators in JavaScript
2. JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Given that x = 10 and y = 5, the table below explains the assignment operators:

3. JavaScript String Operators


The + operator, and the += operator can also be used to concatenate (add) strings. Given that textl "Good ' text2
'Morning" , and text3 = '"' the table below explains the operators:
Operators in JavaScript
4.

Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x = 5, the table below explains the comparison operators•v

Comparing
Returns
false
true
false
true true
true
Operators in JavaScript
5.
not equal value or not equal type
false

less than false


greater than or equal to
less than or equal to true

false

true

Conditional (Ternary) Operator


The conditional operator assigns a value to a variable based on a condition.
Operators in JavaScript
6.

variablename

Syntax
Example explained: If the variable "age" is a value below 18, the value of the variable "voteable" will be "Too young",
otherwise the value of voteable will be "Old enough".
6.Logical Operators
Logical operators are used to detennine the logie between variables or values. Given that x = 6 and y = 3, the table below

explains the logical operators-x


not y) is true
Operators in JavaScript
7.
JavaScript Bitwise Operators
Bit operators work on 32 bits numbers. Any numeric operand in the operation is convefied into a 32 bit number. The result

is converted back to a JavaScript


number.
7. The typeof Operator
The typeof operator retums the type of a variable, object, function or expression:
Operators in JavaScript

typeo+ Returns
string number number boolean object object object function undefined (if myCar
is not declared) object

8. The delete Operator


The delete operator deletes a property from an
object:
var person {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"}; delete person.age; // or
delete person["age"];
9. The in Operator
The in operator returns tme if the specified property is in the specified object, otherwise false:
// Arrays van cars
100" ,
"BMW"];
Operators in JavaScript
"Saab" in Cars Returns false (specify the index number instead of value) a in cars ReturnS
true
1 in cars Returns; true
4 in cars). Returns false (does not exist)
"length" -in cars Returns true (length is an Array property)
// Objects van person = {firstName: "John", lastName: "Doe".
age: 5Ø}g
"firstName" in person // Returns true
"age" in person Returns true
// Predefined objects
'"PI" in Math Returns true
"Nan" in Number Returns true
"length" in String Returns true

10. The instanceof Operator


The instanceof operator retums tme if the specified object is an instance of the specified object:
var cars = ["Saab", "Volvo", "BMW"]; cars
instanceofAnay; // Returns tme cars instanceofObject; // Returns
title cars instanceof String; // Returns false cars
instanceofNumber• // Returns false
11. The void Operator
Operators in JavaScript
The void operator evaluates an expression andreturns undefined. This operator is often used to obtain the undefined
primitive value, using "void(0)" (useful when evaluating an expression without using the retum value).

href="javascript:void(0); ">
Useless link

<a href="javascript:void(document.body. style.backgroundC010F'red');


Click me to change the background color of body to red
Control structure in JavaScript
Control stmcture actually controls the flow of execution of a program. Following are
the several control stmcture supported by JavaScript.
if ... else $f (hour 18) if (time IA) { greeting " Good day", greeting "Good morning switch case else {
} else if (time 2e) { greeting " Good evening' greeting "Good day",

do while loop} else {


while loopgreeting "Good evening"; for loop

If ... else
The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally <script
<script type="text/javascript"> Var grade—IA';

var age = 20; if( age > 18 ){


document.write("<b>Qualifies for driving</b>")• Do
while Loop
Control structure in JavaScript
The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be executed at
least once, even if the condition is false.

<scriptvar
document . Write ("Star—tins
Loop" + do{
"Current
Count count4+;
}while (count < e); document .
write ("Loop stopped!" ) ;

While Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is tme. Once
expression becomes false, the loop will be exited.
<scrip£ type—a-text/javascript"ý
count = a; document Loop" 4 "Or/
While (count < document. "Current Count "+
count + count-+;

document . stoppedl " ) ;


</ script)
Control structure in JavaScript
For Loop
The for loop is the most compact form of looping and includes the following three important parts
The loop initialization where we initialize our counterto a starting value. The initialization statement is executed before
the loop begins.
The test statement which will test if the given conditiOn is tme or not. If condition is true then code given inside the loop
be executedotherwiseloop come out.
decreaseyour counter.
Document Obiect Model or DOM
Document Obiect Model or DOM

Every web page resides inside a browser window which can be considered as an object.
Document Obiect Model or DOM
A Document object represents the HTML document that is displayed in that window.
The Document object has various properties that refer to other objects which allow
access to and modification of document content.
The way a document content is accessed and modified is called the Document Object
Model, or DOM. The Objects are organized in a hierarchy. This hierarchical
structure applies to the organization of objects in a Web document.
Window object — Top of the hierarchy. It is the outmost element of the object hierarchy.
Document object — Each HTML document that gets loaded into a window becomes a
document object. The document contains the contents of the page.
Form object — Everything enclosed in the <form>...</form> tags sets the form object.
Form control elements — The form object contains all the elements defined for that
object such as text fields, buttons, radio buttons, and checkboxes.
N,Thy DOM is required in JavaScript
Document Obiect Model or DOM
JavaScript can change all the HTML elements 111 the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
The DOM is a W3C(Wor1dWide Web Consofiium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platfonn and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a document.
"
Definition:
The HTML DOM is a standard object model and programmmg interface for HTML. It defines:
Document Obiect Model or DOM
The HTML elements as objects
The propefiies of all HTML elements
The methods to access all HTML elements
The events for all HTML elements
In otherwords: The HTML DOM is a standard for how to get, change, add, or deleteHTML
elements.
' <html >
Document Obiect Model or DOM
var

script>

// run this function when the document is


loaded window. on load = function ( ) (l
// create a couple Of elements in an othertÅise empty
HTML page var heading = document. createE1ement ("hl
heading text document . createTextNode ("Big Head!
" heading. appendChi1d (heading text) ;
_
document. body. appendChiId (heading) ;
Document Obiect Model or DOM
Why DOM is required in JavaScript
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
Document Obiect Model or DOM
or change.

document.getElementById(id) //Find an element by element id


document.getElementsByTagName(name) //Find elements by tag
name document.getElementsByClassName(name) //Find elements by
class name Changing HTML Elements
Propelty Description element.inne1HTML= new html content Change the inner
HTML of an element element. attlibute = new value Change the attlibute value of an
HTML element element.style.propefiy= new style Change the style of an HTML
Document Obiect Model or DOM
element Method Description element. setAtfr1bute(att1ibute, value) Change the
attribute value of an HTML element
Adding and Deleting Elements Method Remove an
document. createElement(element) HTML
document.removeChild(element) document. element Add
appendChild(element) an HTML
document.replaceChild(new, old) element
document.write(text) Replace an HTML element
Write into the HTML output stream
Adding Events Handlers
Method

Description
Create an HTML element
Document Obiect Model or DOM
Description
document.getElementById(id). onclick = function() {code} Adding event handler code to an onclick event
Example <img Id="mylmage"
<script> document."landscape.jpg" ;

document.getElementById("p2").style.color= "blue"</script>
document.getElementById("myBtn").addEventListene1("click",
displayDate); element.addEventListener("click", function() { ale1t("Hello
World! });
JavaScript Built in Objects
JavaScript has several built-in or core language objects. These built-in objects are
available regardless of window content
and operate independently of
whatever page your browser has loaded.

Array Object
Multiple values are storea In a single vanaole using Tne Array ooject.
In JavaScript, an array can hold different types of data types in a single slot, which
implies that an array can have a string, a number or an object in a single slot.
An Array object can be created by using following ways:
Using the Array Constructor:
JavaScript Built in Objects
To create empty array when don't know the exact number of elements to be inserted in
an array:
vararrayname = new Array(); example vara = new Array()
To create an array of given size vararrayname = new
Array(size);
Example vara
=new Arrary(l O);
To create an array
with given
elements var
arrayname = new
Array("element 1
JavaScript Built in Objects
Example var a=new
Using the Array Literal Notation:
To create empty array var arrayname example var a=[]; To
create an array when elements are given var arrayname
=["element 1 ","element 2",
Example var
Properties of the Array object
Length - Returns the number of elements in the array.
(array.length) Constructor - Returns the function that created the
Array object. Prototype - Add properties and rnethodsto an object.
Methods of the Array object reverse() - Reverses
the array elements concat() - Joins two or more arrays sort()
- Sort the elements of an array push() - Appends one or more
JavaScript Built in Objects
elementsat the end of an array pop() - Removes and returns
the last element shift() - Removes and returns the first
element
• unshift(), join(), indexOf(), lastlndexOf(), slice(startindex, endindex) are some of the
methods used in Array object.
<script
Array Methods function
Print all item in array cars this
this
document.getElementByld cars;
Student . prototype . age = 15; Student . prototype .
Array as object: { return this. name + + this.
gender
var student = age:20};
Accessing the property of class: var studObj new Student ( ) alert (studObj .
age) ; alert (studObj . getGenderName ( ) ) ;
student.firstName or var fruits = ["Banana", 'Orange", "Apple", •z/ script>

"Mango"]; document.getElementByld("demo").innerHTML =
fruits.join(
fruits.pop(); // Removes the last element ("Mango") from fruits fruits.push("Kiwi"); // Adds a
new element ("Kiwi") to fruits fruits.shift(); // Removes the first element 'Banana" from
fruits(begining) // Adds a new element "Lemon" to fruits(begining)
fruits[fruits.length] = "Kiwi' • // Appends "Kiwi" to fruits delete // Changes the first
element in fruits to undefined fruits.splice(2, O, "Lemont', "Kiwi"); //how many element add
and how many remove
Array Methods
var myGirls= ["sita", "Oita"] • var myBoys= ["mohan", "ram", "hariñ]; var
myChildren = myGirls.concat(myBoys); // Concatenates
(joins) myGirls and myBoys
var fruits = ["Banana", "Orange", 'Lemon , Apple", "Mango"];
varcitrus = fruits.slice(l , 3); //start from I and less than 3 var
citrus = fruits.slice(2); // 2 onwards fruits.sort(); // Sorts the
elements of fruits
// Then reverse the order Of the elements
Object
Date
At timeswhen user need to access the current date and time and also past and future
date and times. JavaScript provides support for working with dates and time through
the Date object.
The Date object provides a system-independentabstraction of dates and times.
Date object can be created as : var today= new Date( );
Dates may be constructed from a year, month, day of the month, hour, minute, and
second, and those six components, as wellas the day of the week, may be extracted
from a date.
Dates may also be compared and converted to a readable string form. A Date is represented
to a precision of one millisecond. new Date() new Date (year, month, day, hours, minutes,
seconds, milliseconds) vard = new Date(); new Date (milliseconds) alert(d); new Date(date
string)
Sat Jun 22 2019 GMT+0545 (Nepal Time)
Object
Date
vard = new
Date(2018, I l, 24, 10,
33; 30, 0); alert(a)
Mon Dec 24 2018
GMT+0545 getUTCFu11Year()
(Nepal
Time) getUTCMilliseconds()

getUTCMinutes() Description
getFullYear()Same as getDate(), getUTCMonth() but returns the UTC date getMonth()Same as
getDay(), but returns the UTC getUTCSeconds() day getDate()Same as getFullYear(), but returns the UTC year
getHours()Same as getHours(), but returns the UTC hour getMinutesOSame as getMilliseconds(), but
returns the UTC milliseconds getSeconds()Same as getMinutes(), but returns the UTC minutes
getMilliseconds() Same as getMonth(), but returns the UTC month

(
getTime()
Object Same as getSeconds(), but returns the UTC seconds
getDay()

Date.now() Setthe (0-23)

set the milliseconds (0.999)


setMinutes() Set the minutes (0-59)
setMontho Set the month (0-1:)
Set the
Set the time 1. 1970)

There is no way to create an instance


Math of the Math object.
Properties of Math
The Math object is used to perform simple and object
complex arithmetic operations.
The Math object provides a number of properties PI -
and methods to work with Number values The
The Math object does not have any constructors. All value
of its methods and properties are static; that is, they of Pi
are member functions of the Math object itself. E - The base of natural logarithm e
Object
LN2 - Natural logarithm of the smallest integer greater than or
2 I-NIO - Natural logarithm equal to a floor(a) - Rounds down.
Returns the largest integer smaller than
of 10 LOG2E - Base 2 or equal to a exp(a) - Returns ea
logarithm of e - Returns ab abs(a) - Returns
LOGIOE - Base 10 logarithm of e absolute value of a random() -
SQRT2 - Square root of 2 Returns a pseudo random number
between O and 1 sqrt(a) - Returns
Methods of Math object max(a,b) - Returns largest of
square root of a sin(a) - Returns sin
a and b min(a,b) - Returns least of a and b round(a) -
of a (a is in radians) cos(a) - Returns
Returns nearest integer ceil(a) - Rounds up. Returns
cos of a (a is in radians)
SQRT1_2 - Square root of 1/2

Math
Math.Pl; // returns 3.141592653589793
Math.pow(8, 2); // returns 64
Object
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.sqrt(64); // returns 8
Math.abs(-4.7); // returns 4.7
Math.floor(4.7); // returns
Math.sin(90 * Math.PI / 180); - // returns 1 (the sine of 90 degrees)
Math.min(O, 150, 30, 20, -8, -200); // returns -200
Math.max(O, 150, 30, 20, -8, -200); // returns 150 Math.random(); // returns a random
number
Regular Expressions
A regular expression is a sequence of characters that forms a search pattern. The
search pattern can be used for text search and text replace operations.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text
search and text replace operations.
Syntax :
[pattern/modifiers;
Examples:
var patt = /mechicampus/i;
Explanation:
/mechicampus/i is a regular expression.
mechicampus is a pattern (to be used in a search).
i is a modifier (modifies the search to be Case-Insensitive).
Note: search(), replace(),match(),test() method can be used to with string.
Regular Expressions
Quantif Description An Matches any string with n at the beginning of it
Metacharacter Description
Matches any string that contains Find a single character. except newline or line terminator
at least one n Find a word character
n* Matches any string that contains zercv or Find a non-word
character Find a digit
more occurrences of n
Find non-digit character
n? Matches any string that contains zero or
As Find a whitespace character
one occurrences of n Find a non-whitespace character
Matches any string that çòntainsa Find a match at the beginning/end of a word. beginning like this:
sequence of X n's "xbHI, end like this: HI
Matches any string that cOhtains Find a match, but not at the beginning/end of a word
a sequence of X to Y n's Find a NUL
character Find a
n{X,} Matches any string that contains a
new line character
sequence of at least X n's
Find a form feed character
n$ Matches any string with n at the Find a carriage return
end of it character Find a tab
character find a vertical
tab character
\xxx Find the character specified by an octal number x,xx
Matches anystring that is followed by a
specific string n Find the character specified by a hexadecimal number cid
Xudddd Find the Unicode character specified by cl hexadecimal number
dddd Matches any string thatis not followed by a specific string n
l<script type " text/
function myFunction ( )

) .value;

Regular Expressions
alert ("Not Math the pattren"

var
y=document . getE1ementByTd .
value ; x=new RegExp (email) ; if(x. test (y) )
"
var passw=
ipformat
alert ("yes
vardateformat= -9] |

Loop in JavaScript
for - loops through a block of code a number of times
2. for/in - loops through the properties of dn object
3. for/of - loops through the values of an iterable object
4. while - loops through a block of code while a specified condition is true
5. do/while- also loops through a block of
code while a specified condition is true
var a
a. length;i++)
alert (a ;
for ( value of a)
alert( value) ;
a = {id:1,name:2,saIary:4} ; for
( value in a) alert( a [value] ) ;
The JavaScript string is an object that represents a sequence of characters. There
are 2 ways to create string in JavaScript.
1. By string literal example var
stringname="string value' 2. By string
object (using new keyword) var
stringname=newString ("string literar') ;
String Object in
JavaScript
Methods Descliption
charAt() It provides the char value present at the specified index.
charCodeAt() 11t provides the Unicode value of a character present at the specified index.
concat() It provides a combination of two or more strings.
indexOf() It provides the position of a char value present in the given string.
lastlndexOf() It provides the position of a char value present in the given string by searching a character
from the last position.
search() match() It searches a specified regular expression in a given string and returns its position if a match
occurs.
replace() substr() It searches a specified regular expression in a given string and returns that regular expression
if a match occurs.
substring()
It replaces a given string with the specified replacement.
slice() It is used to fetch the part of the given string on the basis of the specified starting position
and length.
AtoLowerCase() to
LocaleLowerCase() It is used to fetch the part of the given string on the basis of the specified index.
It is used to fetch the part of the given string. It allows us to assign positive as well negative
toUpperCase() index.
toLocaleUpperCase( It converts the given string into lowercase letter.
) tostring() valueOf() It converts the given string into lowercase letter on the basis of host?s current
locale. It converts the given string into uppercase letter.
It converts the given string into uppercase letter on the basis of host?s current locale.
It provides a string representing the particular object.
It provides the primitive value of string object.

1. charAt(x) Returns the character at the "x" position within the string. var myString = 'jQuery
FTW!I!'.
console.log(myString.charAt(7)); //output F
2. charCodeAt(x) Returns the Unicode Value of the character at
position "x" within the string. //charAt(position) var
message="jquery4u"
)) //output"q"
3. concat(vl, v2,...) Combines one or more
strings (arguments VI v2 etc) into the existing one and returns the combined string.
Original string is not modified.
String Object in
JavaScript
//concat(vl,
var var is an," hopeless
romantic.")
alert(final) //output "Sam is a hopeless romantic.'
4. fromCharCode(c1, c2,...) Returns a string created by using the specified sequence of
Unicode values (arguments cl , c2 etc). Method of String object, not String instance. For
example: String.fromCharCode().
1 21 , 1 22)) //output: abcxyz
console.log(String.fromCharCode(72,69,76,76,79)) //output: HELLO
String Object in
JavaScript
5. indexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. If not found, -1 is returned. "Start"
is an optional argument specifying the position within string to begin the search.
Default is O. varsentence="Hi, my name isSam!" if ) alert("Sam is in there!")
6. lastlndexOf(substr, [start]) Searches and (if found) returns the index number of the
searched character or substring within the string. Searches the string from end to
beginning. If not found, -1 is returned. "Start" is an optional argument specifying the
position within string to begin the search. Default is string.length-l .
7. match(regexp) Executes a search for a match within a string based on a regular
expression. It returns an array of information or null if no match is found. var intRegex=
String Object in
JavaScript
IA [O-9]+$/; var myNumber= '999'; var mylnt = myNumber.match(intRegex);
alert(mylnt);
8. replace(regexp/substr, replacetext) Searches and replaces the regular expression (or
sub string) portion (match) with the replaced text instead. var myString = '999 JavaScript
Coders's console.log(myString.replace(/JavaScript/i, "jQuerV')); //output: 999
jQuery Coders var myString = '999 JavaScript Coders ;
console.log(myString.replace(new RegExp( "999", "gi" ), "The")); //output: The
JavaScript Coders
9. search(regexp) Tests for a match in a string. It returns the index of the match, or -1 if not found.
var intRegex = /[0-9 _()+J+$/,. var myNumber = '999'; var islnt =
myNumber.search(intRegex); console.log(islnt); //output: O
String Object in
JavaScript
10. slice(start, [end]) Returns a substring of the string based on the "start" and "end" index
arguments, NOT including the "end" index itself. "End" is optional, and if none is specified, the
slice includes all characters from "start" to end of string.
//slice(start, end)
var
text.slice(O,4 //returns "exce'
text.slice(2,4 //returns "cet
11. split(delimiter, [limit]) Splits a string into many according to the specified
delimiter, and returns an array containing each element. The optional "limit" is an
integer that lets you specify the maximum number of elements to return.
String Object in
JavaScript
//split (delimiter) var message="Welcome to
jQueryaut //word[O] contains "We

//word[l] contains "lcome to jQuery4u'


varword=message.split("l");
12. substr(start, [length]) Returns the characters in a string beginning at "start" and
through the specified number of characters, "length" "Length" is optional, and if
omitted, up to the end of the string is assumed. //substring(from, to) var
text.substring(O,4) //returns "excel text.substring(2,4) //returns "ce'
13. substring(from, [to]) Returns the characters in a string between "from" and "to" indexes,
NOT including "to" inself. "To" is optional, and if omitted, up to the end
of the string is assumed. //substring(from, [to]) var myString =
String Object in
JavaScript
'javascript rox'; myString = myString.substring(O, 1 0); console.log(myString) //output:
javascript
14. toLowerCase() Returns the string with all of its characters converted to lowercase.
//toLowerCase() var myString = 'JAVASCRIPT ROX'; myString =
myString.toLowerCase(); console.log(myString) //output:javascript rox
15. toUpperCase() Returns the string with all of its characters converted to uppercase.
var myString = 'javascript rox'; myString =
myString.toUpperCase();
console.log(myString) //OUtPUt: JAVASCRIPT
ROX
Define and invocation function in JavaScript
JavaScript functions are defined with the function keyword.
You can use a function declaratiorvor a function expression.
Function Declarations
function

functionName(parameters) { // code
to be executed
html>
<bodp
<h2>JavaScript Functions</h2>
Define and invocation function in JavaScript
9>This example callsa function which performs a calculation and returns the result:</p>
id="demo"></p>
<script> varx= myFunction(4, 3);
document.getElementByld("demo").innerHTML =
x; function myFunction(a, b) { return a * b;

varx = function (a, b) {returna * b};


varx = function (a, b) {returna * b}; varz
= x(4, 3);
Note: After a function expression has been stored in a variable, the variable can be
used as a function:
Define and invocation function in JavaScript
The function bellowis actually an anonymous function (a function withouta name).
varmyFunction = function (a, b) {return a * b}; varx = myFunction(4, 3);
anonymous self-invoking function function () { varx = "Hello!!"; // I will invoke
myself
function
myFunction(a,
b) { return a *
b; varx =
myFunction(4,
3) * 2; vartxt =
myFunction.toString();
Define and invocation function in JavaScript
Arrow Functions //
ES5 varx =
function(x, y)
{ return x * y;
// ES6 const x = (x, y)
=> x * y;
Event in JavaScript
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
An HTML event can be something the 'browser does, or something a user does.
Here are some examples of HTML events:
An HTML web page has finished loading

An HTML input field was changed


An HTML button was clicked
An HTML mouse over to html components
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
Event in JavaScript
HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.

Example:
<button .innerHTML = time is?</button>
<button onclick="this.innerHTML = Date()">The time is?</button>
<button onclick="displayDate()">The time is?</button>
Event Description onchange An HTML element has
been changed onclick The user clicks an HTML element
onrnouseover The user moves the mouse overan HTML element
Event in JavaScript
onrnouseout The user moves the mouse away from an HTML
element onkeydown The user pushes a keyboard key onload
The browser has finished loading the page

6 onFocus It OCCUS when an object takes the 'focus'. Sn Function


7 onLoad It OCCwS when a page is loaded.
8 onMouseOver It occwrs when the mouse cwrsor moves over an object.
9 onMouseOUt It OCCUS when the mouse cursor moves off an object.
Application
10 onSeIect It occurs when the user selects text in a text area.
It OCCUS when the user clicks the *'submit' button on a
11 onSubmit
form.
12 onUnIoad It occurs when the user leaves a document.
Event in JavaScript
onAbort It occurs when the user stops the loading of an image.
It occurs when anc)bject on the page is no longer the
2 onBlur
'focUS'.
3 onChange It occwrs when a text field is changed by the user.
4 onCIick It occtgrs when the User clicks an object.
5 on Error
It occurS when d document or image can't load correctly.
Event in JavaScript
<img
SRC = cei.jpg onClick =
"alert(Welcome to Computer Educational

<img onDblClick =
"alert(Welcometo Computer Educational

<INPUT type = text onKeyDown = 'Valert('Key pressed


Welcome to Computer Educational
<INPUT type = text onKeyDown = "alert('Key pressed Welcome to Computer Educational
text onBlur= "alert ('Lost focws from here........')"> //change the cursor
position or lose focus
<form name = forml onsubmit= "return validate();">
<input type = submit value = " send 's
Event in JavaScript
action='tcei form.jsp" onsubmit="return validate form()"
method='Þost'>80
Form validation
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and useful. Typical
validation tasks are:
has the user filled in all required fields?
has the user entered a valid date?
has the user entered text in a numericfleld?
Most often, the purpose of data validation Is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways. It is
important to validate the form submitted by the user because it can have inappropriate values.
So, validation is must to authenticate user.
Form validation
JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server-side validation. Most of the web developers prefer JavaScript form validation.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.

Attribute Description
disabled Specifies that the input element should be disabled
max Specifiesthe maximum value of an input element
min Specifiesthe minirnumvalueof an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
Form validation
type Specifies the type of an input element
Form validation
Example: Automatic validation x =
.value; <input required>
if
Form validation
text = "Input not valid';
Form validation
text = "Input OK";
Form validation
Form validation
else txt = "Input OK"; document.
Form validation
<Iabe1>Mobi1e Number</ label>
< input type t' text" name— "mobile" max length "10
<div class—I' error" id—
</div>
< labe

<option>United States</option>
<option>United Kingdom</option>
< / select>
<div class—I' error"
Form validation
</div>
<div class ' row" >
<1abe1>Gender< / label >
<div class form—inline I' > type radio" name
"gender" type "radio" name
"gender" value Female</l
< / div>
<div class I' error" id I'
</div>

<Iabel>Hobbies
<div

<input type="
Form validation
<Iabel>Hobbies
<div

<input type="
<div class="

Sport:
>
Form validation
Music
< / div>
< / div>
<div class="

< / div>
Form validation
function pruntError (elemld, hxntMsg) { document .
getE1ementById (elemld) . innerHTML — hintMsg ;

function validateForm ( )
// Retrieving the values of form elements var name
= document . contactForm. name . value; var email =
document. contactForm. email. value; var mobile =
document. contactForm.mobiIe.va1ue; var country =
document. contactForm. country. value ; var gender =
document. contactForm. gender .value; var hobbies
var checkboxes = document. getE1ementsByName
( "hobbies"
Form validation

; i < checkboxes . length; i++)


// Defining error variables U with a default value var nameErr =
emailErr — mobiLeErr = countryErr genderErr true ;
/ / Validate
name if (name
' 'Please enter your name"
Form validation
printError
} else var regex if (regeÝ, test (name) false) {
[a—zA—
printError ( " nameErr" "Please enter a valid
name
} else { printError ( "
nameErr" nameErr =
false;

// Defining error variables U with a default value


// Validate email address if (email printError ( "
email Err 'z' Please enter your email address "
Form validation
} else {
// Regular expression for basic email validation var regex
if(regex . test (email) false) { printËrror ( "email Err " "Please
enter a valid email address"

printError (" emailErr"


email Err = false;
Form validation
// Validate mobile number if (mobile printError
("mobileErr' "Please enter your mobile number"
} else { var regex /A [1-9] if (regex. test (mobile) false) {
printError ( "mobileEtr" "Please enter a valid 10 digit mobile nur
} else{ printnrror
( "mobileErr"
mobileErr = false;

// Validate country if (country " Select "


printError ( 'countryErr" "Please select your country"
Form validation
printError ( countryErr"
countryErr = false;
Form validation
"Mobile Number : + mobile +
"Country: + country + gender if (hobbies.
length) { dataPreview "Hobbies : + hobbies. join(

// Display input data in a dialog box before submitting the form alert (dataPreview) ;
Cookies
What are Cookies?
Cookies are data, stored in small text files, on your computer.
When a web server has sent a web page to a browser, the connection is shut down, and the server
forgets everything about the user.
Cookies were invented to solve the problem 'how to remember information about the used':
When a user visits a web page, his/her name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his/her name
When a browser requests a web page from a server, cookies belonging to the page are added to
the request. This way the server gets the necessary data to "remember t information about users.
How to create cookie document.cookie = "username=mohan' t we can also add an expiry date (in
UTC time). By default, the cookie is deleted when the browser is closed:
document.cookie= "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
How to read a cookie:
Cookies
varx = document.cookie: //x is array
Delete a Cookie with JavaScript
Deleting a cookie is very simple.
You don't have to specify a cookie valuewhen you delete a cookie.
Just set the expires parameter to a passed date: 72 document.cookie= "username=;
expires=Thu, 01 Jan 1970 00:00:00 UTC;

Cookie Pros
Convenience: Cookies not only remember which websites you have been to, they also remember information
about forms.
Personalization: cookie ca be used for serving up personalized content that is geared towards that specific user's
preferences. Amazon I-JSeS cookies to offer you related products, Google Uses cookies to better understand your
searches, and Facebook Uses cookies to do just about everything.
Cookies
Effective Advertising: How nice would it be to only be offered products or services that are relevant to
you? Internet marketing companies collect data from cookies to run marketing campaigns aimed at a very
specific market segment including product group, geolocation, search term, and demographics.
Ease of Control: It is actually really easy to manage your cookies if YOU know how. Most browsers make it
easy for you to clear your browsing history. Just go to tools, clear history and select cookies. Cookies are
stored on your hard drive in a text file under cookie.txt, and since it is a text file you can use just about any
viewer or text editor to display, edit, and delete them.
Cookie Cons
Privacy: The main concern for most users is privacy. Cookie enabled web browsers keep track of all the
websites you have visited.
Security: Cookie security is a large problem. The concern is that many security holes have been found in different
browsers. Some of these holes were so serious that they allowed malicious webmasters to gain access to users'
email, different passwords, and credit card information.
Secrecy: Although third party cookies can be blocked through your browser settings, most people don't have the
technical expertise to do this. Most browsers purposely make it difficult to find this setting in order to prevent you
from turning them off. No cookies mean no data, which in turn means less money.
Cookies

if (document .cookie . length !

= var nameVa1ueArray = document . cookie . split (


document . getE1ementByTd ( "bcolor" ) . value =
nameVa1ueArray [I] ; document . bgC010r = nameVa1ueArray
[1] ;

function setC010rCookie ( ) var selectedVa1ue = document .


getE1ementById ("bcolor" . value ;
Cookies
(selectedVa1ue Select Color"

if (selectedVa1ue != "Select Color"


K/ script> < / h tm1> document . bgC010r — selectedVa1ue ; document .
</head> cookie=" cOIor— ' +seIectedVa1ue+" ; expires=Fri ,
UTC;'
•elect
<option
<option
<option
apt ion
K/ select> "bcolor onchange
setCoIorCookie ( ) ; " > value " Select
</bodÿ> Color">Se1ect Color</option> value red" /
option> value I' green I' / option > value "blue
Cookies
"
>B
1u
e<
/
op
ti
on
>
setlnterval function
The setlnterval() method calls a function or evaluates an expressionat specified intervals (in
milliseconds).
The setlnterval() method will continue calling the function until clearlnterval() is called, or the
window is closed.
The ID value returned by setlnterval() is used as the parameter for the clearlnterval() method.
Tip: 1000 ms= I second.
Tip: To execute a functionoñly once, after a specified numberof milliseconds, use the
setTimeout()
method. e!DocrvPE html>
'html >
'body
html> method executes
between
(html > backgr
Togglingc/button»
script on this page starts this A script on this page starts this clock:
<button
var nyVar setlnterval(setCoIor, 3ee);
myVar = setlnterval (myTimer, 108) ; Stop
function myTimer() {function setColor() ( var d = new Date(); var x • time document. var t = d. toLoca1eTimeString(); document.
getE1ement8yId ( "demo " ) . innerHTML
function mystopFunction() {
clearlnterval (myVar) ; function stOpCOIor()
{ clearlnterval (nyVar) ;
</ body> ascript>
O'bodys
</html)

setTimeout function
The setTimeout() rnethod calls a function or evaluates an expression after a
specified number of milliseconds.
Tip: 1000 ms= 1 second.
Tip: The function is only executed once. If you need to repeat execution, use the setlnterval() method.
Tip: Use the clearTimeout() method to prevent the function from running.
< !DOCTYPE html*
(html >

the button to wait 3 seconds, then aler£


(button " >Try it</buttonS the button to open a new window and close the window after
three seconds (388' (scripty var myVar;
'">Open
function myFunction() { myVar = setTimeout(a1ertFunc,
3øee);
function openWin() { van myWind0i.J = window. open("", "mywindow",
"width=2ae, height—lee");

function alertFunc() { is 'mywindow• myWindow. close() }, 308);


</ body>
</ html)
C/ html>

77

Dialog Boxes in JavaScript


The dialog box is a graphical control element ih the form of a small window that communicates
information to the user and prompts them for a response. Dialog boxes are classified as "modal" or
"modeless", depending on whether they block interaction with the software that initiated the dialog.
A modal dialog temporarily locks you out pf the rest of an application until it is closed. While a rnodal
dialog box is open, it will always be the top window of the application— no other windows will be in
front of it.
A modeless dialog allows you to use the rest of the application while it is open. It can be hidden by
other application windows.
I . Alert Dialog Box: An alert dialog box is the most simple dialog box. It enables you to
display a short message to the user. It also includes OK button, and the user has to click this
OK button to continue. var message = "Hi there! Click OK to continue."; alert(message);
/* The following line won't execute until you dismiss previous alert */
alert("This is another alert box.");
2. confirm dialog box allows user to confirm or cancel an action. A confirm dialog looks similar to an alert
dialog but It includesa Cancel button along with the OK button. var result = confirm("Are you sure?");
if(result) document.write("You clicked OK button!"); else document.write("You clicked Cancel button!");

Dialog Boxes in JavaScript


3' The prompt dialog box is used to prompt the user to enter information. A prompt dialog box includes a
text input field, an OK and a Cancel button. var name = prompt("What's your name? ); O
&& name != 'hull") { document.write("Hi, " + name);
} else
{ document.write("Anonymous!");
var age = Number(prompt('What's your age?")); //type casting

You might also like