Chap 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

CHAPTER-2

Front End Development


2.1 Java Script: An introduction to JavaScript
JavaScript DOM Model
Date and Objects
Regular Expressions
Exception Handling
Validation-Built-in objects-Event Handling,
DHTML with JavaScript-
JSON introduction – Syntax – Function Files – Http Request –SQL.
An introduction to JavaScript
• JavaScript is a very powerful client-side scripting language.
• JavaScript is used mainly for enhancing the interaction of a user with the
webpage. .
• JavaScript is also being used widely in game development and Mobile
application development.
• JavaScript supports dynamic scripting.
• It is lightweight and mostly used as an integral part of web pages where there is
need of client side script and dynamic pages.
• Javascript supports Object Oriented concepts.
• JavaScript is usually embedded directly into HTML pages
• So, JavaScript is a client-side scripting language that runs entirely inside the web
browser.
History
• JavaScript was created by Brendan Eich (co-founder of Mozilla) in
1995 during his time at Netscape Communications
• It was inspired by Java, Scheme and Self
• Originally called Mocha (a name chosen by Marc Andreessen)
• In Sep 1995 the name was changed to LiveScript
• Then, in Dec 1995, upon receiving a trademark license from Sun, the
name JavaScript was adopted
• The general-purpose JavaScript engine had been embedded in web
browsers (Netscape, IE, etc..)
History
• The ECMA-262 (European Computer Manufacturer’s Association) Specification defined a
standard version of JavaScript language
• ECMAScript Edition 1 First standardized version of JavaScript
• ECMAScript Edition 2 is the second official standard
• ECMAScript 3 (ES3) was released in December 1999.
• More advanced language, Includes regular expressions and exception handling
• ECMAScript 4 (ES4) A new standard includes features such as JSON (JavaScript Object
Notation) & class based object-oriented programming
• ECMAScript 5 (ES5) was released in December 2009. It adds in getter and setter
properties, introduces features for robust programming via a strict mode and JSON
handling arrays
• ECMAScript 6 (ES6) was released in June 2015, and is the latest official version of
JavaScript
Features of JavaScript
• It is lightweight, interpreted client-side scripting language.
• It supports object-oriented capabilities.
• Open and cross-platform (machine independent).
• JavaScript is a case-sensitive language.
• The user input is validated before sending the page to the server. This
minimizies the server traffic which tends to minimize the load on the
sever.
• Interactive interfaces like drag drop components or sliders can be
created which can give responses to user.
Advantages of JavaScript
• JavaScript is executed on the client side – The code is executed on the user's
processor instead of the web server – This means less load on server.
• No need to go to the server, hence execution is fast.
• JavaScript is relatively easy language – The JavaScript language is relatively
easy to learn and comprises of syntax that is close to English
• Increased interactivity: We can create interfaces that react when the user.
• Immediate response to user’s actions which enables more interactivity.
• Richer interfaces: You can use JavaScript to include such items as
drag-and-drop components and sliders to give a rich interface to your site
visitors.
• There is no need of development tools which are expensive. A simple text
editor like notepad can be used to write the scripts.
Disadvantages of JavaScript
• JavaScript cannot write to files on the server without the help of a
server side script – Ajax, JavaScript can send a request to the server
• JavaScript cannot access back-end databases without a server side
script
• JavaScript cannot read from or write to files in the client – Even
though JavaScript is running on the client computer (the one where
the web page is being viewed) it is not allowed to access anything
outside of the web page itself – This is done for reasons of security
• JavaScript does not have multi-threading – JavaScript does not have
multi-threading capabilities
Java Vs JavaScript
JAVA JAVASCRIT
1.Java is compiled,Object-Oriented Programming language 1. JavaScript is interpreted,Object-Oriented client side
created by james Gosling of Sun Microsystem later occupied scripting language created by Brendan Eich at Netscape and
by Oracle. originally known as LiveScript.
2.It is an independent languge which is executed by JVM 2.JS must be executed along with HTML by web browser and
that needs to be complied into byte code and has the file has file extension as .js.
extension as .java.
3. JS can be coded by using any text editor like notepad and
3.To code and debug in Java, we need JDK(Java Sublime text.
Development Kit) and specific IDEs such as NetBeans and
Eclipse. 4.JavaScript supports dynamic type of checking for
programs.
4.Java supports Static type of checking for programs.
5.JavaScript is weakly typed language and have more
5.Java is strongly typed language and variable must be relaxed syntax and rules.
declare first to use in program.In Java the type of a variable
is checked at compile-time. 6.JavaScript requires less memory therefore it is used in web
pages but is less secure as compared to Java.
6.Java program uses more memory and is more secure as
compared to JavaScript. 7.Javascript has event based approach to concurrency .i.e.
concurrency is based on a queue system called “event loop”
7.Java has a thread based approach to concurrency. that supports features like asyn/await function in coding.
8.Java supports multithreading. 8.Javascript doesn’t support multi-threading.
9.It is used for mobile application development, desktop 9.It is dominantly used for making interactive web
application development,web servers, embedded applications.
system,etc.
JAVASCRIPT SYNTAX
• JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page.
• You can place the <script> tags, containing your JavaScript, anywhere within you web page, but it
is normally recommended that you should keep it within the <head> tags.
• The <script> tag alerts the browser program to start interpreting all the text between these tags
as a script.
• So, syntax will look as follows:
• <script language="javascript" type="text/javascript">
JavaScript code
</script>
• The script tag takes two important attributes:
1. Language: This attribute specifies what scripting language you are using. Typically, its value will
be JavaScript.
2. Type: Type attribute is used to specify that the file type is text file and contains JavaScript code.
Using JS in an HTML(Embedded, External)
• JavaScript Placement in HTML File(Embedded)
<html>
<body>
There is a flexibility given to include
<script language="javascript" JavaScript code anywhere in an HTML
type="text/javascript"> document.
JavaScript code But there are following most
preferred ways to include JavaScript
</script> in your HTML file.
</body> • Script in <head>...</head> section.
</html> • Script in <body>...</body> section.
JS PROGRAM
• PROGRAM
<html>
<body>
<script language="javascript" type="text/javascript">
document.write ("Hello World!")
</script>
</body>
</html>
• This code will produce the following result: Hello World!
• Description:
• The <script type="text/javascript"> tag tells the browser that whatever comes between that
tag and the coming </script> tag is script.
The type="text/javascript" tells it that it is JavaScript.
document.write: this method write string into HTML document.
JavaScript Popup Boxes
• JavaScript has three kinds of popup boxes:
1. Alert Box: - is used if you want to make sure information comes
through to the user.
• Syntax: alert("sometext");
2. Confirm Box: - is used if you want the user to verify or accept
something. When a confirm box pops up, the user will have to
click either "OK" or "Cancel" to proceed.
• If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
• Syntax: confirm("sometext");
3.Prompt Box: - is used if you want the user to input a value
before entering a page.
• When a prompt box pops up, the user will have to click either
"OK" or "Cancel" to
proceed after entering an input value. If the user clicks "OK" the
box returns the input
value. If the user clicks "Cancel" the box returns null.
• Syntax: prompt("sometext","defaultvalue");
JavaScript in External File
• JavaScript in External File
• As you begin to work more extensively with JavaScript, you will be
likely to find that there are cases where you are reusing identical
JavaScript code on multiple pages of a site.
• You are not restricted to be maintaining identical code in multiple
HTML files. The script tag provides a mechanism to allow you to store
JavaScript in an external file and then include it into your HTML files.
• Here is an example to show how you can include an external
JavaScript file in your HTML code using script tag and its src attribute.
JavaScript in External File
• External JavaScript code for demonstrating welcome message
• External JavaScript file is saved by extension “.js”
• Eg- write the following content in notepad and save that file as
MyFile.js and then include the JavaScript file into html page. It calls
the JavaScript function on button click.
• function msg()
{
alert("welcome to the world of web");
}
JavaScript in External File
In these in p1.html file external JS MyFile.js is linked using script tag and src
attribute
p1.html
<html>
<head>
<script language="JavaScript" src="MyFile.js">
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="Click Here"onclick="msg( )"/>
</form>
</body>
</html>
Advantages of external javascript
• There will be following benefits if a user creates an external javascript:
• It helps in the reusability of code in more than one HTML file.
• It allows easy code readability.
• It is time-efficient as web browsers cache the external js files, which
further reduces the page loading time.
• It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
• The length of the code reduces as only we need to specify the location
of the js file.
Disadvantages of external files
• There are the following disadvantages of external files:
• The stealer may download the coder's code using the url of the js file.
• If two js files are dependent on one another, then a failure in one file may
affect the execution of the other dependent file.
• The web browser needs to make an additional http request to get the js code.
• A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
• We need to check each file that depends on the commonly created external
javascript file.
• If it is a few lines of code, then better to implement the internal javascript
code.
JavaScript Output

• JavaScript can "display" data in different ways:


• Writing into an HTML element , using innerHTML.
• Writing into an HTML output , using document.write().
• Writing into an alert box , using window.alert().
Using innerHTML
• To access an HTML element, JavaScript can use the document.getElementById(id) method.
• The id attribute defines the HTML element. The innerHTML property defines the HTML content:

<!DOCTYPE html>
<html>
<body>

<h2>My First Web Page</h2>


<p>My First Paragraph.</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6; OUTPUT
</script> My First Web Page
My First Paragraph.
</body> 11
</html>
Using document.write()
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using window.alert()
• You can use an alert box to display data:
• <!DOCTYPE html>
• <html>
• <body>

• <h2>My First Web Page</h2>


• <p>My first paragraph.</p>

• <script>
• window.alert(5 + 6);
• </script>

• </body>
• </html>
Variables in JS
• Variables are the names given to the memory location where we can store
some values.
• 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).
1.Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
sign.
2.After first letter we can use digits (0 to 9), for example value1.
3.JavaScript variables are case sensitive, for example x and X are different
variables.
4.JavaScript variables can also hold other types of data, like text values .
5. In JavaScript a text like "John Doe" is called a string.
6.When you assign a text value to a variable, put double or single quotes around
the value.
7.When you assign a numeric value to a variable, do not put quotes around the
value. If you put quotes around a numeric value, it will be treated as text.
Variables in JS
8.JavaScript Variables are declared using the “var” keyword. Syntax: var num; var carname;
9.JavaScript variables can be declared with initial value. Syntax: var num=1; var carname=”volvo”;
10.Multiple JavaScript variables can even be declared at the same time.
Syntax: var num=1; var name= “Bikila”;
11.Every JavaScript variables ends with semicolon (;)
Example of JavaScript variable
Let’s see a simple example of JavaScript variable.
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Variables in JS
• JavaScript local variable
• A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only.
• For example:
<script>
function abc()
{
var x=10;//local variable
}
</script
Variables in JS
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:
<html>
<body>
<script>
var data=200;//global variable
function a(){
document.write(data);
}
function b() {
document.write(data);
}
a(); //calling JavaScript function
b();
</script>
</body>
</html>
Variables in JS
• To declare JavaScript global variables inside function, you need to use window object.
• Now it can be declared inside any function and can be accessed from any function. For
example:
• <html>
• <body>
• <script>
• function m(){
• window.value=100;//declaring global variable by window object
• }
• function n(){
• alert(window.value);//accessing global variable from other function
• }
• m();
• n(); </script> </body>
• </html>
Datatypes in JS
• JavaScript provides different data types to hold different types of
values.
• There are two types of data types in JavaScript.
1.Primitive data type
2.Non-primitive (reference) data type
• JavaScript has dynamic types. This means that the same variable can be
used as different types.
• var x // Now x is undefined
• var x = 5; // Now x is a Number
• var x = "John"; // Now x is a String
Datatypes in JS
• There are five types of primitive data types in JavaScript. They are as follows:
• Data Type Description
• String represents sequence of characters e.g. "hello"
• Number represents numeric values e.g. 100
• Boolean represents boolean value either false or true
• Undefined represents undefined value
• Null represents null i.e. no value at all
• JavaScript non-primitive data types
• The non-primitive data types are as follows:
• Data Type Description
• Object represents instance through which we can access members
• Array represents group of similar values
• RegExp represents regular expression
Datatypes in JS
• JavaScript Arrays
• var cars=new Array();
• cars[0]="Saab";
• cars[1]="Volvo";
• cars[2]="BMW";
• or (condensed array): var cars=new Array("Saab","Volvo","BMW");
• JavaScript Objects - An object is delimited by curly braces. Inside the braces the object's
properties are defined as name and value pairs (name : value).
• The properties are separated by commas:
• var person={firstname:"John", lastname:"Doe", id:5566};
• name=person.lastname;
• name=person["lastname"];
Datatypes in JS
• Undefined and Null
• Undefined is the value of a variable with no value.
• Variables can be emptied by setting the value to null.
• cars=null;
• person=null;
• Declaring Variable Types
• When you declare a new variable, you can declare its type using the "new" keyword:
• JavaScript variables are all objects.
• When you declare a variable you create a new object.
• var carname=new String;
• var x= new Number;
• var y= new Boolean;
• var cars= new Array;
• var person= new Object;
OPERATORS
• Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator.
• Operators are the symbols that perform operations on operand.
• JavaScript supports the following types of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
• typeof Operators.
JavaScript Objects and Data Type conversion
• Everything" in JavaScript is an Object: a String, a Number, an Array, a Date.
• In JavaScript, an object is data, with properties and methods.
• In JavaScript, objects are data (variables), with properties and methods. var txt = "Hello";
Methods: txt.indexOf(),txt.length() Accessing Object Properties
• The syntax for accessing the property of an object is: objectName.propertyName
• This example uses the length property of the String object to find the length of a string:
• var message="Hello World!"; var x=message.length;
• JavaScript is a dynamically typed language
• We can convert a number in to string and vice versa
• parseInt method - used to convert a string value, which is holding a number data type
• temp = parseInt(“42”)
• anoth = parseInt(“54.34”)
• Str=””+2500;
• Str=””+temp;
• Simply adding an empty quote to a number value will convert a number into string data type.
Functions in JS
• A function consists of the “function” keyword followed by the name of the function, a set
• of open and close parentheses enclosing an optional parameter list and a body enclosed in
• a set of curly braces.
• Syntax: function functionName(parameterList)
{
// body
}
Function parameters are separated by commas in the function declaration.
• A function uses the return keyword to return a value from a function.
• JavaScript code found in a function is not executed until the function is called
• Example
function myFunction(p1, p2)
{
return p1 * p2; // The function returns the product of p1 and p2
}
Functions in JS
• Function Invocation
• The code inside the function will execute when "something" invokes (calls)
the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
• Advantages:
• You can reuse code: Define the code once, and use it many times.
• You can use the same code many times with different arguments, to
produce different results.
Date Object
• The Date object is used to work with dates and times. Date objects are created with the Date()
constructor.
• Examples
• Get today's date.
<html>
<body>
<script>
var d=new Date();
document.write(d);
</script>
</body>
</html>
• Example:
• To store the current date in a variable called "my_date":
• var my_date=new Date()
• After creating an instance of the Date object, you can access all the methods of the object from the "my_date" variable.
• If, for example, you want to return the date (from 1-31) of a Date object, you should write the following:
• my_date.getDate()
• You can also write a date inside the parentheses of the Date() object, like this:
• new Date("Month dd, yyyy hh:mm:ss")
• new Date("Month dd, yyyy")
• new Date(yy,mm,dd,hh,mm,ss)
• new Date(yy,mm,dd)
• new Date(milliseconds)
• Here is how you can create a Date object for each of the ways above:
• var my_date=new Date("October 12, 1988 13:14:00")
• var my_date=new Date("October 12, 1988")
• var my_date=new Date(88,09,12,13,14,00)
• var my_date=new Date(88,09,12)
• var my_date=new Date(500)
ARRAY METHODS IN JS
• JavaScript Array Methods
• The Array object has many properties and methods which help developers to handle
arrays easily and efficiently. You can get the value of a property by specifying
arrayname.property and the output of a method by specifying arrayname.method().
• length property --> If you want to know the number of elements in an array, you can
use the length property.
• prototype property --> If you want to add new properties and methods, you can use
the prototype property.
• reverse method --> You can reverse the order of items in an array using a reverse
method.
• sort method --> You can sort the items in an array using sort method.
• pop method --> You can remove the last item of an array using a pop method.
• shift method --> You can remove the first item of an array using shift method.
• push method --> You can add a value as the last item of the array.
• <html>
• <head>
• <title>Arrays!!!</title>
• <script type="text/javascript">
• var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
• Array.prototype.displayItems=function(){
• for (i=0;i<this.length;i++){
• document.write(this[i] + "<br />");
• } }
• document.write("students array<br />");
• students.displayItems();
• document.write("<br />The number of items in students array is " + students.length + "<br />");
• document.write("<br />The SORTED students array<br />");
• students.sort();
• students.displayItems();
• document.write("<br />The REVERSED students array<br />");
• students.reverse();
• students.displayItems();
• document.write("<br />THE students array after REMOVING the LAST item<br />");
• students.pop();
• students.displayItems();
• document.write("<br />THE students array after PUSH<br />");
• students.push("New Stuff");
• l>
• < students.displayItems();
• document.write("<br />THE students array after PUSH<br />");
• students.push("New Stuff");
• students.displayItems();
• </script>
• </head>
• <body>
• </body>
• </html>
DOM- Document Object Model
DOM stands for Document Object Model and is responsible for how various objects
in a document interact with each other. DOM is required for developing web
pages, which includes objects like paragraphs, links, etc. These objects can be
operated to include actions like add or delete. DOM is also required to add extra
capabilities to a web page. On top of that, the use of API gives an advantage over
other existing models.
JavaScript can access all the elements in a web page using the Document Object
Model (DOM). The web browser creates a DOM of the webpage when the page is
loaded.
Using DOM, JavaScript can perform multiple tasks. It can create new elements and
attributes, change the existing elements and attributes and even remove existing
elements and attributes.
According to W3C DOM is platform language interface that allows the program and
scripts to dynamically access and update the content, structure and style of the
document.
DOM- Document Object Model
Hierarchy of Objects in web documents: DOM LEVELS
Properties and Methods of Document Object
• HTML DOM Methods are actions we can perform on
HTML elements
• HTML DOM Properties are values that we can set or
change <script>
• document.getElementById("ex").innerHTML = "Hello
World!"; </script>
• getElementById -> Method
• innerHTML -> Property
JavaScript Animation
• The JavaScript animation is implemented as gradual changing of DOM
element styles or canvas objects
• The whole process is split into pieces, and each piece is called by
timer
• An animation is created by replacing one Image frame with another
at speed such that it appears to be a moving Image
• Animations can be created using JavaScript by using a timer which
replaces one image frame with another
• The two timer function setTimeout() and setInterval() to execute
JavaScript codes at set intervals
JavaScript Animation
EVENTS IN JS
• Events are the actions that result from activities, such as clicking a link or filling a form by the user.
• An event handler is required to manage the proper execution of all these events.
• Event handlers are an extra attribute of the object. This attribute includes the event's name and the action taken if the
event takes place.
• JavaScript can also react to existing events and create new events in the page.
• getElementById, innerHTML Example
• getElementById: To access elements and attributes whose id is set.
• innerHTML: To access the content of an element.
• Event handler Example
• createElement: To create new element
• removeChild: Remove an element
• you can add an event handler to a particular element like this
• document.getElementById(id).onclick=function()
• {
• lines of code to be executed
• }
• OR
• document.getElementById(id).addEventListener("click", functionname)
• For exception handling and Regression refer w3school.com

You might also like