Unit 1
Unit 1
Unit 1
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:
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
<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:
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
false
true
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
typeo+ Returns
string number number boolean object object object function undefined (if myCar
is not declared) object
href="javascript:void(0); ">
Useless link
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';
<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-+;
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>
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()
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
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;
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
<img onDblClick =
"alert(Welcometo Computer Educational
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
// 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
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 >
77