Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
61 views76 pages

CMPN Ip Module-2.

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 76

Module:2 Front End Development

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
JavaScript

• There is variety of scripting languages used to develop dynamic


websites. JavaScript is an interpreted scripting language.
• An interpreted language is a type of programming language
that executes its instructions directly and freely without
compiling machine language instructions in precious program.
• Program is a set of instructions used to produce various kinds
of outputs. JavaScript was initially created to "make webpages
alive". The programs in this language are called scripts.
3.1.1 Features of JavaScript :
• JavaScript is light weight scripting language because it does not support all features of object-
oriented programming languages.
• No need of special software to run JavaScript programs
• JavaScript is object-oriented scripting language, and it supports event-based programming facility.
It is case sensitive language.
• JavaScript helps the browser to perform input validation without wasting the user's time by the
Web server access.
• It can handle date and time very effectively.
• Most of the JavaScript control statements syntax is same as syntax of control statements in other
programming languages.
• An important part of JavaScript is the ability to create new functions within scripts. Declare a
function in JavaScript using function keyword.
• Software that can run on any hardware platform (PC, Mac, SunSparc etc.) or software platform
(Windows, Linux, Mac OS etc.) is called as platform independent software. JavaScript is platform
independent scripting language. Any JavaScript-enabled browser can understand and interpreted
JavaScript code. Due to different features, JavaScript is known as universal client-side scripting
language.
There are two types of scripting : Server-side scripting and Client-side scripting.
• Client-side Scripting : In this type, the script resides on client computer (browser)
and that can run on the client. Basically, these types of scripts are placed inside
an HTML document.
• Server-side Scripting : In this type, the script resides on web server. To execute
the script, it must be activated by client then it is executed on web server.
Example
• Between the body tag of html
• Between the head tag of html
• In .js file (external javaScript)
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used
to add information about the code, warnings or suggestions so that end user
can easily interpret the code.
1. To make code easy to understand
2. To avoid the unnecessary code

There are two types of comments in JavaScript.


• Single-line Comment
• Multi-line Comment
JavaScript syntax
JavaScript syntax is the set of rules, how JavaScript programs are constructed:
// How to create variables:
var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;
JavaScript variable
• A JavaScript variable is simply a name of storage location. There are two
types of variables in JavaScript : local variable and global variable.
• There are some rules while declaring a JavaScript variable (also known as
identifiers).
• Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
sign.
• After first letter we can use digits (0 to 9), for example value1.
• JavaScript variables are case sensitive, for example x and X are different
variables.
var x = 10;  
var _value="son";
Example:
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
local variable
A JavaScript local variable is declared inside block or function. It is accessible
within the function or block on
<script>  
function abc()
{  
var x=10;//local variable  
}  
</script> 
JavaScript global variable
It is accessible from any function. A variable i.e. declared outside the function or declared with window object is
known as global variable.
For example:
<script>  
var data=200;//global variable  
function a(){  
document.writeln(data);  
}  
function b(){  
document.writeln(data);  
}  
a();//calling JavaScript function  
b();  
</script>
To declare JavaScript global variables inside function, you need to
use window object.
For example:
function m(){  
window.value=100;//declaring global variable by window object  
}  
function n(){  
alert(window.value);//accessing global variable from other function  
}  
Internals of global variable in JavaScript
When you declare a variable outside the function, it is added in the window
object internally. You can access it through window object also.
Example:
var value=50;  
function a(){  
alert(window.value);//accessing global variable   

JavaScript HTML DOM

• With the HTML DOM, JavaScript can access


and change all the elements of an HTML
document.
• HTML DOM (Document Object Model): When
a web page is loaded, the browser creates
a Document Object Model of the page.
• The HTML DOM model is constructed as a tree
of Objects:
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
• 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
What is the HTML DOM?
The HTML DOM is a standard object model and programming
interface for HTML. It defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change,
add, or delete HTML elements.
The DOM Programming Interface
• The HTML DOM can be accessed with JavaScript (and with other
programming languages).
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of
an HTML element).
• A method is an action you can do (like add or deleting an HTML element).
• The following example changes the content (the innerHTML) of the <p> element with id="demo”.
<p id="demo">hello world</p>
<script>
onClick=“document.getElementById("demo").innerHTML
</script>

<button type=“button”
onClick=“document.getElementById("demo").style.color=‘red’ “>

</button>
getElementById is a method,
innerHTML is a property. It is used to get or change any html element.
3.3 Objects in JavaScript
• JavaScript is an object-based scripting language. Almost everything is an object in
JavaScript. A JavaScript object is an entity having state (properties) and behavior
(methods). An object can group data together with functions needed to
manipulate it. Look around you, you will find many examples of real-world objects.
Such as table, board, television, bicycle, shop, bus, car, monitor etc. All these
tangible things are known as objects. Take an example of car object. It has
properties like name, model, weight, color etc. and methods like start, stop, brake
etc. All cars have same properties but contain different values from car to car. All
cars have same methods but perform differently.
Properties and methods of object's are accessed with '.' operator.
JavaScript supports 2 types of objects built-in objects and user
defined objects.
1. Built in objects such as Math, String, Array, Date etc.
2. JavaScript gives facility to create user defined objects as per
user requirements. The ‘new’ keyword is used to create new
object in JavaScript.
e.g.
d= new Date();
// ‘d’ is new instance created for Date object.
Following are some of the predefined methods and properties for DOM object.

Property Description

head Returns the <head> element of the document

title Sets or returns title of the document.

URL Returns full URL of the HTML document.

body, img Returns <body>, <img> elements respectively.

Method Description

write() Writes HTML expressions or JavaScript code to a document.

Same as write(), but adds a newline character after each


writeln()
statement.

There are many ways of accessing form elements, of which the


getElementById() easiest is by getElementById() method. In which id property is
used to find an element
The innerHTML Property
• The innerHTML property is useful for getting html element and changing
its content. The innerHTML property can be used to get or change any
HTML element, including <html> and <body>
const
• Const keyword is mainly used to store that variable whose value is not
going to changed. Const is more powerful than var. once used to store a
variable it cannot be reassigned.
const name= ‘Yash’;
Console.log(name);// will print Yogesh to the console
Name=‘Akash’;
Console.log(name);// trying to reassign a const variable and will give error.
Let
The variable declared will be mutable i.e. their value can be changed. It
work like the var keyword with some key difference like scoping which
make it a better option as when compared to var.

Let name= ‘Yogesh’;


console.log(name);// Yogesh
name=‘akash’;
console.log(name);// akash
example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Date Object :
The date object is used to create date and time values. It is created using
new keyword. There are different ways to create new date object.
var currentdate=new Date();
var currentdate=new Date(milliseconds);
var currentdate=new Date(dateString);
var currentdate=new Date(year, month, day, hours, minute, seconds,
milliseconds);
Array Object :
• An array is an object that can store a collection of items. JavaScript arrays are
used to store multiple values in single variable. An array is a special variable
which can hold more than one value at a time. Arrays become really useful
when you need to store large amounts of data of the same type. You can
create an array in JavaScript as given below.
var fruits=["Mango","Apple","Orange","Grapes"]; OR
var fruits=new Array("Mango","Apple","Orange","Grapes");
• You can access and set the items in an array by referring to its indexnumber
and the index of the first element of an array is zero. arrayname[0] is the first
element, arrayname[1] is second element and so on.
e.g. var fruitname=fruits[0];
document.getElementById("demo").inner HTML=fruits[1];
Window Object :
• At the very top of the object hierarchy is the window object. Window
object is parent object of all other objects. It represents an open
window in a browser. An object of window is created automatically by
the browser. Window object represents an open window in a browser.
An object of window is created automatically by the browser.
Following table shows some of the methods and properties for
window object.
<!DOCTYPE html>
<html>
<head>
<title >Window Opener and Closer </title>
<script type="text/javascript">

function makeNewWindow()
{
var newwin=window.open();
newwin.document.write("<h1>This is new window</h1>");
newwin.document.body.style. backgroundcolor="skyblue";
}
</script>
</head>
<body>
<form>
<input type="button" value="Create New Window” onClick="makeNewWindow()">
</form></body>
</html>
<!DOCTYPE html> <html>
<head>
<script type="text/javascript"> function sampleFunction()
{
window.setTimeout(next, 4000);
}
function next()
{
alert("4 seconds have passed");
}
</script></head>
<body style="background-color:cyan"> <h1
align="center">
Click button and wait for message </h1>
<input type="button" value="Timeout function"
onClick="sampleFunction()"> </body>
</html>
3.5 JavaScript Built-in Objects
JavaScript has several built-in or core language objects. These
built-in objects are available regardless of window content and
operates independently of whatever page browser has loaded.
These objects provide different properties and methods that are
useful while creating live web pages.

String Object :
• String is used to store zero or more characters of text within
single or double quotes. String object is used to store and
manipulate text.
Example :
var str="Information Technology";
document.write ("length of string is :-" + str.length);
document.write ("Substring is :-" + str.substr (12,10));
Math Object :
The built-in Math object includes mathematical constants and
functions. You do not need to create the Math object before using it.
Following table contains list of math object methods:
e.g. var x=56.899; alert(Math.ceil(x));
JavaScript Form Validation

• It is important to validate the form submitted by the user


because it can have inappropriate values. So, validation is must
to authenticate user.
• 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.
• Through JavaScript, we can validate name, password, email,
date, mobile numbers and more fields.
JavaScript Form Validation Example
• In this example, we are going to validate the name and password. The name
can’t be empty and password can’t be less than 6 characters long.

if (name==null || name==""){  
  alert("Name can't be blank");  
  return false;  
}else if(password.length<6){  
  alert("Password must be at least 6 characters long.");  
  return false;  
  }  
}  
JavaScript Retype Password Validation
<script type="text/javascript">  
function matchpass(){  
var firstpassword=document.f1.password.value;  
var secondpassword=document.f1.password2.value;  
if(firstpassword==secondpassword){  
return true;  
}  
else{  
alert("password must be same!");  
return false;  
}  } 
JavaScript Form Validation
HTML form validation can be done by JavaScript.
• If a form field (fname) is empty, this function alerts a message,
and returns false, to prevent the form from being submitted:
function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  if (x == "") {
    alert("Name must be filled out");
    return false;
  }
}
HTML Form Example
<form name="myForm" action="/
action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Regular Expression
• A regular expression is a pattern of characters.
• The pattern is used to do pattern-matching "search-and-replace" functions on text.
• In JavaScript, a RegExp Object is a pattern with Properties and Methods
example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Regular Expressions</h2>
<p>Do a case-insensitive search for "w3schools" in a string:</p>
<p id="demo"></p>
<script>
let text = "Visit W3Schools";
let pattern = /w3schools/i;
let result = text.match(pattern);
document.getElementById("demo").innerHTML = result;
</script>
</body>
</html>
Exception Handling in JavaScript
• An exception signifies the presence of an abnormal condition which
requires special operable techniques. In programming terms, an exception
is the anomalous code that breaks the normal flow of the code. Such
exceptions require specialized programming constructs for its execution.
What is Exception Handling
• In programming, exception handling is a process or method used for
handling the abnormal statements in the code and executing them. It also
enables to handle the flow control of the code/program. For handling the
code, various handlers are used that process the exception and execute
the code. For example, the Division of a non-zero value with zero will
result into infinity always, and it is an exception. Thus, with the help of
exception handling, it can be executed and handled.
• In exception handling:
• A throw statement is used to raise an exception. It means when an
abnormal condition occurs, an exception is thrown using throw.
• The thrown exception is handled by wrapping the code into the try…
catch block. If an error is present, the catch block will execute, else
only the try block statements will get executed.
• Thus, in a programming language, there can be different types of
errors which may disturb the proper execution of the program.
Types of Errors
• While coding, there can be three types of errors in the code:
• Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language, a
syntax error may appear.
• Runtime Error: When an error occurs during the execution of the program, such an error is known
as Runtime error. The codes which create runtime errors are known as Exceptions. Thus, exception
handlers are used for handling runtime errors.
• Logical Error: An error which occurs when there is any logical mistake in the program that may not
produce the desired output, and may terminate abnormally. Such an error is known as Logical error.
Error Object
• When a runtime error occurs, it creates and throws an Error object. Such an object can be
used as a base for the user-defined exceptions too. An error object has two properties:
1. name: This is an object property that sets or returns an error name.
2. message: This property returns an error message in the string form.
• EvalError: It creates an instance for the error that occurred in the eval(), which is a global
function used for evaluating the js string code.
• InternalError: It creates an instance when the js engine throws an internal error.
• RangeError: It creates an instance for the error that occurs when a numeric variable or
parameter is out of its valid range.
• ReferenceError: It creates an instance for the error that occurs when an invalid reference is
de-referenced.
• SyntaxError: An instance is created for the syntax error that may occur while parsing the
eval().
• TypeError: When a variable is not a valid type, an instance is created for such an error.
• URIError: An instance is created for the error that occurs when invalid parameters are passed
in encodeURI() or decodeURI().
Exception Handling Statements
There are following statements that handle if any exception occurs:
• throw statements
• try…catch statements
• try…catch…finally statements.
A try…catch is a commonly used statement in various programming
languages. Basically, it is used to handle the error-prone part of the code. It
initially tests the code for all possible errors it may contain, then it
implements actions to tackle those errors (if occur). A good programming
approach is to keep the complex code within the try…catch statements.
• try{} statement: Here, the code which needs possible error testing is kept
within the try block. In case any error occur, it passes to the catch{} block
for taking suitable actions and handle the error. Otherwise, it executes
the code written within.
syntax
catch{} statement: This block handles the error of the code by
executing the set of statements written within the block. This block
contains either the user-defined exception handler or the built-in
handler. This block executes only when any error-prone code needs to
be handled in the try block. Otherwise, the catch block is skipped.
try{  
expression; } //code to be written.  
catch(error){  
expression; } // code for handling the error.  
<html>
<head> Exception Handling</br></head>
<body>
<script>
try{
var a= ["34","32","5","31","24","44","67"]; //a is an array
document.write(a); // displays elements of a
document.write(b); //b is undefined but still trying to fetch its value. Thus catch block
will be invoked
}catch(e){
alert("There is error which shows "+e.message); //Handling error
}
</script>
</body>
</html>
JavaScript Events
• The change in the state of an object is known as an Event.
• In html, there are various events which represents that some activity
is performed by the user or by the browser.
• When javascript code is included in HTML, js react over these events
and allow the execution.
• This process of reacting over the events is called Event Handling.
Thus, js handles the HTML events via Event Handlers.
Mouse events:

Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.


Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & When the user press


onkeyup and then release the
key
Form events:
Event Performed Event Handler Description

focus onfocus When the user focuses on


an element

submit onsubmit When the user submits the


form

blur onblur When the focus is away


from a form element

change onchange When the user modifies or


changes the value of a
form element
Window/Document events
Event Performed Event Handler Description

load onload When the browser finishes


the loading of the page

unload onunload When the visitor leaves the


current webpage, the
browser unloads it

resize onresize When the visitor resizes


the window of the browser
Click event eg:
<html>  
<head> Javascript Events </head>  
<body>  
<script language="Javascript" type="text/Javascript">  
    <!--  
    function clickevent()  
    {  
        document.write("This is IP lecture");  
    }  
    //-->  
</script>  
<form>  
<input type="button" onclick="clickevent()" value="Who's this?"/>  
</form>  
</body>  
</html>  
Mouse Over Event
<html>  
<head>   
<h1> Javascript Events </h1>  
</head>  
<body>  
<script language="Javascript" type="text/Javascript">  
    function mouseoverevent()  
    {  
        alert("This is  IP Lecture");  
    }  
   </script>  
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>  
</body>  
</html> 
Focus Event
<html>  
<head> Javascript Events</head>  
<body>  
<h2> Enter something here</h2>  
<input type="text" id="input1" onfocus="focusevent()"/>  
<script>  
<!--  
    function focusevent()  
    {  
        document.getElementById("input1").style.background=" aqua";  
    }  
//-->  
</script>  
</body>  
</html> 
Keydown Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
DHTML JavaScript
• JavaScript can be included in HTML pages, which creates the content of
the page as dynamic. We can easily type the JavaScript code within the
<head> or <body> tag of a HTML page. If we want to add the external
source file of JavaScript, we can easily add using the <src> attribute.
• Example -The following example simply uses
the document.write() method of JavaScript in the DHTML. In this
example, we type the JavaScript code in the <body> tag.
• <HTML>  
• <head>  
• <title>  
• Method of a JavaScript  
• </title>  
• </head>  
• <body>  
• <script type="text/javascript">  
• document.write("JavaScript");  
• </script>  
• </body>  
• </html> 
JSON
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent 
• The JSON format is syntactically similar to the code for creating
JavaScript objects. Because of this, a JavaScript program can easily
convert JSON data into JavaScript objects.
Json Syntax
• JSON syntax is derived from JavaScript object notation syntax:
• Data is in name/value pairs
• Data is separated by commas
• Curly braces hold objects
• Square brackets hold arrays
Json Data
• JSON data is written as name/value pairs (aka key/value pairs).
• A name/value pair consists of a field name (in double quotes), followed by a colon,
followed by a value:
{"name":"John”}
JSON Values
• In JSON, values must be one of the following data types:
• a string
• a number
• an object
• an array
• a boolean
• null
JSON Function Files
• A common use of JSON is to read data from a web server, and display the data in a web
page.

<div id="id01"></div>
<script>
function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i<arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]
2: Create a JavaScript function to display the array. 
Create a function myFunction() that loops the array objects, and display the content as HTML links:

function myFunction(arr) {
    var out = "";
    var i;
    for(i = 0; i < arr.length; i++) {
        out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
    }
    document.getElementById("id01").innerHTML = out;
}
3: Use an array literal as the argument (instead of the array variable):
Call myFunction() with an array literal as argument:

myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
4: Put the function in an external js file
Put the function in a file named myTutorials.js:

myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
JSON Http Request
• A common use of JSON is to read data from a web server, and display
the data in a web page.
<!DOCTYPE html>
<html>
<body>

<div id="id01"></div>

<script>
var xmlhttp = new XMLHttpRequest();
var url ="file:///Users/amitaylani/Downloads/sample3.txt";

xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>

</body>
</html>

You might also like