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

Mean Stack

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 166

MEAN Stack

Session-1
Topics to be covered…
 What is Scripting Language
 Client vs. Server Side Scripting
 Introduction to JavaScript
 Where JavaScript is used
 Variables in Javascript
 JavaScript Console
 Let keyword
 Use Strict Keyword
 Javascript Hoisting
 JS Operators
 Function
 Control Structure and loops
 Write(),alert(),confirm() and prompt() box
 DOM Events
 Global Properties and methods
The scripting language is basically a language
where instructions are written for a run time
environment. They do not require the compilation
step and are rather interpreted.
Programming for the World Wide Web involves
Server-side programming
Client-side (browser-side) programming
What is JavaScript?
JavaScript is used to program the behaviour of web pages
(performing dynamic tasks).

JavaScript are scripts (code) that is executed on the


client’s browser instead of the web-server (Client-side
scripts).

JavaScript is lightweight and cross-platform and loosly


coupled.
JavaScript was created by Brendan Eich, a Netscape
Communications Corporation programmer, in
September 1995.
Why we need client side programming
•The user’s actions will result in an immediate response
because they don't require a trip to the server.

•Allows the creation of faster and more responsive web


applications.

• Make web pages more interactive

•Fewer resources are used and needed on the web-server.


JavaScript Features

Light Weighted
Case Sensitive Scripting Language

Control Statement Interpreter Based


JavaScript
In-Built Function Features Event Handling

Looping Statement If…Else Statement

Client Side Technology Validating User’s Input

Object-Based Scripting Language


What Javascript can do?
• Javascript can change HTML Content
• Javascript can change HTML Attributes
• Javascript can change HTML Styles (CSS)
• Javascript can validate Data
• Javascript can Make Calculations
EmbeddingJavaScript in HTML
1. Anywhere in the html file between <script></script> tags.

2. In an external file and refer to it using the SRC attribute.


JavaScript Display Possibilities

JavaScript can "display" data in different ways:


1. Writing into the browser console, using console.log().

2. Writing into the HTML output using document.write().

3. Writing into an alert box, using window.alert().

4. Writing into an HTML element, using innerHTML.


Console Object
The Console object provides access to the browser's debugging
console.

Console Object Methods:

log() method: writes a message to the console.

Syntax
console.log(message)
table() Method: writes a table in the console view.
clear() Method: clears the console.
The console.clear() method will also write a message in the console: "Console
was cleared".

Syntax
console.clear()
Alerts
An alert box is often used if you want to make sure information
comes through to the user.

Syntax
window.alert("sometext");

alert("I am an alert box!");


Prompts and Confirm
Prompts :The return is the data the user entered

Confirm: The confirm returns true and false


Variables
JavaScript variables are containers for storing data values..
Variables are declared with the 'var' keyword.
var a=10;

Lexical Scoping:
Depending on position meaning changes.
Data Types

DataTypes

Number Boolean null


String undefined
(object)

var x=10;
alert(typeof(x));
undefined value and null value
Undefined value means the variable is declared but not assigned.

Ex.
var x;
console.log(x);
x=10;

null value means the variable is declared and assigned as null means
noting neighter number nor string or boolean.

var x=null;
console.log(x);
Declaring are Assigning variables
var x=10; //Declare and Assigning

var t; //Declaring
var t=20; //Assigning

y=10; //Declaring auto and Assigning


"use strict"
The strict mode in JavaScript does not allow following things:

• Use of undefined variables


• Use of reserved keywords as variable or function name
• Duplicate properties of an object
• Duplicate parameters of function
• Assign values to read-only properties
• Modifying arguments object

"use strict";
x = 3.14; // This will cause an error because x is not declared
JavaScript Hoisting

Hoisting is JavaScript's default


behavior of moving
all declarations to the top of the current scope
(to the top of the current script or the current function).

<script>
function f1()
{ var x;
alert(x);
Declaration if(1==1)
moves {
To top var x=10;
}
}
f1()
</script>
let
let allows you to declare variables that are limited in scope to the block, statement,
or expression on which it is used. This is unlike the var keyword, which defines a
variable globally, or locally to an entire function regardless of block scope.

<script>
{
let x = 10;
console.log(x);
}
console.log(x);
</script>
Javascript Operators
typeof: operator returns a string indicating the type of the unevaluated
operand.

Syntax:
typeof operand

The following table summarizes the possible return values of


typeof
Arithmetic Operator
Addition (+) Operator:
The addition operator produces the sum of numeric operands or string concatenation.
Subtraction (-) Operator

Multiplication (*) Operator

Division (/) Operator


Comparisons operators
Equality (==) operators
The equality (==) operator converts the operands if they
are not of the same type, then applies strict comparison.

Syntax:
A==B

1 == 1 // true
'1' == 1 // true
1 == '1' // true
0 == false // true
0 == null // false
Identity / strict equality (===) operators
The identity (===) operator returns true if the operands
are strictly equal with no type conversion.

Synatx:
A===B

1 === 1 // true

1 === ‘1' // false


if Statements
if-else statement is used to execute the code whether condition
is true or false.

if(condition)
{
//Statement 1;

}
Else
{
//Statement 2;
}
Switch Statement
Switch is used to perform different actions on different conditions.
It is used to compare the same expression to several different
values.
switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
.
.
case condition n:
//Statements;
break;
default:
//Statement;
}
Loops
for(initialization; test-condition;
for Loop: increment/decrement)
{
//Statements;
}

while (condition)
While Loop {
//Statements;
}

do
Do-While Loop {
//Statements;
}
while(condition);

for...in loop is used to loop through an object's properties.


Events
Events are actions or occurrences that happen in the system you are
programming, which the system tells you about so you can respond to them in
some way if desired.

For example, if the user clicks a button on a webpage, you might want to
respond to that action by displaying an information box.

<script type="text/javascript">
function click_event()
{
document.write("Button is clicked");
}
</script>
</head>
<body>
<button onclick="click_event()">Click Me</button>
</body>
window.open()

Opens the new window.


syntax
var window = window.open(url, windowName, [windowFeatures]);

A DOM String indicating the URL of the resource to be loaded. This can be a path or
URL to an HTML page, image file, or any other resource which is supported by the
browser. If the empty string ("") is specified as url, a blank page is opened into the
targeted browsing context.

<script>
function openwin(){
mywin=window.open("Page1.html“,””,”width=200,height=200,top=200,left=100”);
}
</script>
window.close()
closes the current window
syntax
window.close();

<script>
window.close();
</script>
window.print()

prints the contents of the window.


syntax
window.print();

<script>
window.print();
</script>
JavaScript Global Properties & methods
Infinity: A numeric value that represents positive/negative infinity

NaN: "Not-a-Number" value

eval(): Evaluates a string and executes it as if it was script code

isFinite(): Determines whether a value is a finite, legal number

isNaN(): Determines whether a value is an illegal number

Number(): Converts an object's value to a number

parseFloat(): Parses a string and returns a floating point number

parseInt(): Parses a string and returns an integer


END
Session-2
Topics to be covered…
 JavaScript Array
 JavaScript Array Methods
 JavaScript String
 String Methods
 JavaScript Dates Get/Set
Methods
 JavaScript Math Object
 JavaScript RegEx
Array
JavaScript array is an object that represents a collection of similar type of
elements.

Array indexes start with 0. [0] is the first array element, [1]
is the second, [2] is the third ...

By array literal:

var arrayname=[“value1”,”value2”.....”valueN”];

By using an Array constructor (using new keyword):

var arrayname=new Array(“value1",“value2",“value3");


<script>
var emp=new Array(“one",“two",“three");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

Output:
one
two
three
Array Properties
length property: The length property of an object which is an instance of type
Array sets or returns the number of elements in that array.

Syntax: array.length

<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("array length is : " + arr.length);
</script>
Array-methods
concat(): Returns a new array comprised of this array joined with
other array(s) and/or value(s).

Syntax:
array.concat(value1, value2, ..., valueN);

toString(): Returns a string representing the array and its elements.

Syntax:
array.toString();

join(): Joins all elements of an array into a string.


It behaves just like toString(), but in addition we can specify the separator.

Syntax:
array.join(separator);
pop():
Removes the last element from an array and returns that element.
Syntax:
array.pop();

push():
Adds one or more elements to the end of an array and returns the new
length of the array.
Syntax:
array.push(element1, ..., elementN);

shift():Removes the first element from an array and returns that


element.
Syntax:
array.shift();

unshift(): Adds one or more elements to the front of an array and


returns the new length of the array.
Syntax:
array.unshift( element1, ..., elementN );
splice():Adds and/or removes elements from an array.
Syntax:
array.splice(index, howMany, [element1][, ..., elementN]);

index − Index at which to start changing the array.


howMany − An integer indicating the number of old array elements to remove.
If howMany is 0, no elements are removed.
element1, ..., elementN − The elements to add to the array. If you don't
specify any elements, splice simply removes the elements from the array.

slice(): Extracts a section of an array and returns a new array.


Syntax:
array.slice( begin [,end] );

It does not remove any elements from the source array.


sort()Sorts the elements of an array
Syntax:
array.sort( );

array.sort(compareFunction);

When the sort() function compares two values, it sends the values to the compare
function, and sorts the values according to the returned (negative, zero, positive)
value

<script type="text/javascript">
var num = [10,20,20,10];
num.sort(function (a , b) {
console.log(a +" & " + b + " " + (a-b));
});
</script>
indexOf():Returns the first (least) index of an element within the array
equal to the specified value, or -1 if none is found.
Syntax:
array.indexOf(searchElement[, fromIndex]);

lastIndexOf(): Returns the last (greatest) index of an element within the


array equal to the specified value, or -1 if none is found.
Syntax:
array.lastIndexOf(searchElement[, fromIndex]);

reverse(): Reverses the order of the elements of an array -- the first


becomes the last, and the last becomes the first.
Syntax:
array.reverse();
Array.forEach()
The forEach() method calls a function (a callback function) once for each array element.

Array.map()
The map() method creates a new array by performing a function on each array
element.
The map() method does not execute the function for array elements without values.
The map() method does not change the original array.

Array.filter()
The filter() method creates a new array with array elements that passes a test.

Array.reduce()
The reduce() method reduces the array to a single value.
String Object
The String object is a constructor for strings, or a sequence of characters.

Syntax:
var s = new String(string);

Length:Returns the length of the string.

Special Characters:
String Methods
charAt():Returns the character at the specified index
Syntax:
string.charAt(index);
index − An integer between 0 and 1 less than the length of the string.
Return Value
Returns the character from the specified index.

charCodeAt()Returns a number indicating the Unicode value of the character


at the given index.
Syntax:
string.charCodeAt(index);

match():Used to match a regular expression against a string.


Syntax:
string.match( param )
param − A regular expression object.
replace()Used to find a match between a regular expression and a string, and to replace the
matched substring with a new substring.
Syntax:
string.replace(regexp/substr, newSubStr/function[, flags]);

<script>
var re = "apples";
var str = "Apples are round, and apples are juicy.";
var newstr = str.replace(re, "oranges");
document.write(newstr ); To replace case insensitive, use
</script> a regular expression with an /i flag
(insensitive):

To replace all matches, use a regular


expression with a /g flag (global
match)
search()Executes the search for a match between a regular expression and
a specified string.
Syntax:
string.search(regexp);

Str.toLowerCase(): Returns the calling string value converted to lower


case.

Str.toUpperCase(): Returns the calling string value converted to


uppercase.

endsWith():Checks whether a string ends with specified string/characters


split()Splits a String object into an array of strings by separating the
string into substrings.
Syntax:
string.split([separator][, limit]);

var x1 = (“Welcome to infoway technologies pune ".split());


var x2 = (" Welcome to infoway technologies pune ".split(" "));
var x3= (" Welcome to infoway technologies pune ".split(" ", 2));

substr()Returns the characters in a string beginning at the specified


location through the specified number of characters.
Syntax:
string.substr(start[, length]);

document.write( str.substr(-2,2));

document.write(str.substr(1));
document.write( str.substr(-20,2));
substring()Returns the characters in a string between two indexes into
the string.
Syntax:
string.substring(indexA, [indexB])

localeCompare(): Returns a number indicating whether a reference string


comes before or after or is the same as the given string in sort order.
Syntax:
string.localeCompare( param )

0 − If the string matches 100%.


1 − no match, and the parameter value comes before the stringobject's value in the locale sort
order
-1 −no match, and the parameter value comes after the string object's value in the local sort
order
Math object
The JavaScript Math object allows you to perform mathematical tasks
on numbers.

Math.round(x) returns the value of x rounded to its nearest integer

Math.pow(x, y) returns the value of x to the power of y

Math.sqrt(x) returns the square root of x

Math.abs(x) returns the absolute (positive) value of x

Math.ceil(x) returns the value of x rounded up to its nearest integer

Math.floor(x) returns the value of x rounded down to its nearest integer

Math.min() and Math.max() can be used to find the lowest or highest


value in a list of arguments
Math.random() returns a random number between 0
(inclusive), and 1 (exclusive).

Math.floor(Math.random() * 10); // returns a number between 0


and 9

Math.floor(Math.random() * 11); // returns a number between 0


and 10

Math.floor(Math.random() * 100); // returns a number between 0


and 99

Math.floor(Math.random() * 10) + 1; // returns a number between 1


and 10

Math.floor(Math.random() * 100) + 1; // returns a number between 1


and 100
Date Object
A date consists of a year, a month, a day, an hour, a minute, a second,
and milliseconds.
Date objects are created with the new Date() constructor.
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
<script>
var d = new Date();
document.write(d.getDay());
</script>

Date set Methods:

<script>
var d= new Date();
d.setFullYear(2020, 0, 14);
document.write(d);
</script>
Regular Expressions
Regular Expression Modifiers

Quantifiers

$ : Matches character at the end of the line.


.: Matches only period.
^ : Matches the beginning of a line or string.
- : Range indicator. [a-z, A-Z]
[0-9] : Find any character between the brackets (any digit)
[^0-9] : Find any character NOT between the brackets (any non-digit)
[abc] : Find any character between the brackets
[^abc] : Find any character NOT between the brackets
(x|y)Find any of the alternatives specified
[a-z] : It matches characters from lowercase ‘a’ to lowercase ‘z’.
[A-Z] : It matches characters from uppercase ‘A’ to lowercase ‘Z’.
\w: Matches a word character and underscore. (a-z, A-Z, 0-9, _).
\W: Matches a non word character (%, #, @, !).
\d: Find a digit
\s: Find a whitespace character
{M, N} : Donates minimum M and maximum N value.

RegEx Object Methods:


exec(): Tests for a match in a string. Returns the first match
test(): Tests for a match in a string. Returns true or false
END
Session-3 & 4
Topics to be covered…
 DOM Methods
 DOM Document
 DOM Elements
 DOM HTML
 DOM CSS
 DOM Animations
 DOM Event Listener
 JavaScript Form Validation
 DOM Nodes
HTML DOM
The document object represents the whole html document.

When a webpage loads in the browser. browser creates a DOM for the
page.

Document:- Html Page


Object:- Elements and attributes
Model:- Tree Structure of HTML elements
By the help of document object, we can add dynamic content to our web
page.

The DOM is a W3C (World Wide Web


Consortium) standard.
Why we should learn HTML DOM:w3 standard to understand the
structure of html page so that we can create ,read, update and
delete and manage DOM elements using JavaScript and jQuery
methods.

HTML DOM helps you to understand and control the element


structure using JavaScript methods.
DOM Methods

document.write("string") writes the given string on the


document.

document.getElementById() returns the element having the


given id value.

getElementsByName() returns all the elements having


the given name value.

getElementsByTagName() returns all the elements


having the given tag name.

getElementsByClassName() returns all the elements


having the given class name
innerHTML Property

The innerHTML property can be used to write the dynamic html


on the html document.

Syntax:
document.getElementById(id).innerHTML = new HTML

<script>
document.getElementById("para").innerHTML = "New text!";
</script>

<p id="para">Old text!</p>


innerText Property

The innerText property sets or returns the text content of the


specified node.

Syntax:
document.getElementById(id).innerText = text

<script>
document.getElementById("para").innerText = "New text!";
</script>

<p id="para">Old text!</p>


DOM createElement()

The createElement() method creates an Element Node with the specified


name.
syntax
var element = document.createElement(tagName);

var para= document.createElement(“p");


DOM createTextNode()

To add text to the element we have to create a textnode first.

syntax
var node= document.createTextNode(“text”);

var node = document.createTextNode("This is a new


paragraph.");
HTML DOM textContent Property

The textContent property sets or returns the textual content of the


specified node.
syntax
node.textContent = text

Para.textContent="This is a new paragraph.";


HTML DOM setAttribute() Method
The setAttribute() method adds the specified attribute to an element,
and gives it the specified value.
syntax
element.setAttribute(attributename, attributevalue)
DOM Node.appendChild()

The Node.appendChild() method adds a node to the end of the list of


children of a specified parent node.
syntax
Node.appendChild()
<div id="div1">
</div>

<script>
var para = document.createElement("p");
var node =
document.createTextNode(“Infoway”);
para.appendChild(node);

var element =
document.getElementById("div1");
element.appendChild(para);
</script>
HTML DOM EventListener
The addEventListener() method attaches an event handler to the
specified element.
You can add many event handlers to one element

Syntax:
element.addEventListener(event, function);

<button id="myBtn">Handler</button>

<script>
document.getElementById("myBtn").addEventListener("click",
myFunction);

function myFunction() {
alert ("Hello World!");
}
</script>
Event Bubbling or Event Capturing?
Event propagation is a way of defining the element order when an
event occurs. If you have a <p> element inside a <div> element, and
the user clicks on the <p> element, which element's "click" event
should be handled first?

In bubbling the inner most element's event is handled first and then
the outer: the <p> element's click event is handled first, then the
<div> element's click event.

In capturing the outer most element's event is handled first and then
the inner: the <div> element's click event will be handled first, then
the <p> element's click event.

Syntax:
addEventListener(event, function, useCapture)

default value is false which will use the bubbling propagation,


END
Session-5
Topics to be covered…
 Canvas Methods
 JavaScript Window
 JavaScript Screen
 JavaScript Location
 JavaScript History
 JavaScript Navigator
 JavaScript Timing
setTimeout()
setInterval()
 JavaScript Objects
 Properties and Methods
Canvas

a. The HTML <canvas> element is used to draw graphics on a web page.


b. Canvas has several methods for drawing paths, boxes, circles, text, and
adding images.

Step 1: Find the Canvas Element


var canvas = document.getElementById("myCanvas");

Step 2: Create a Drawing Object


var ctx = canvas.getContext("2d");
Draw a Line:
moveTo(x,y) - defines the starting point of the line
lineTo(x,y) - defines the ending point of the line

var canvas = document.getElementById(“CN");


var ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

Draw a Circle:
beginPath() - begins a path
arc(x,y,r,startangle,endangle) - creates an arc/curve.
var canvas = document.getElementById(“CN");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 10, 0, 2 * Math.PI);
ctx.stroke();
Drawing Text on the Canvas:
var canvas = document.getElementById(“CN");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText(“Welcome", 10, 50);

Add Color and Center Text:


var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText(“Welcome", 50,50);
Window location object
The window.location object can be used to get the current
page address (URL) and to redirect the browser to a new
page.

window.location.href returns the href (URL) of the current page

window.location.hostname returns the domain name of the web host

window.location.pathname returns the path and filename of the current


page

window.location.protocol returns the web protocol used (http: or https:)

window.location.port property returns the number of the internet host


port (of the current page).
Window History object

The window.history object contains


the browsers history.

history.back() - same as clicking back in the browser

history.forward() - same as clicking forward in the browser

history.go() - loads the given page number.

history.back(); //for previous page


history.forward(); //for next page
history.go(2); //for next 2nd page
history.go(-2); //for previous 2nd page
Window navigator object
The JavaScript navigator object is used for browser detection.
It can be used to get browser information such as appName,
appCodeName etc.

appName returns the name


appVersion returns the version
appCodeName returns the code name
cookieEnabled returns true if cookie is enabled otherwise false
language returns the language
platform returns the platform e.g. Win32.
online returns true if browser is online otherwise false..
JS Timer
Window.setTimeout() Method:
Executes a function, after waiting a specified number of milliseconds.

Syntax:
setTimeout(function, milliseconds);

The first parameter is a function to be executed.


The second parameter indicates the number of
milliseconds before execution.

<button onclick="setTimeout(myFunction,
3000)">SetTimeout</button>

<script>
function myFunction() {
alert('Hello');
}
</script>
Window.setInterval() Method

The setInterval() method repeats a given function at every given


time-interval.

Syntax:
setInterval(function, milliseconds);

The first parameter is the function to be executed.


The second parameter indicates the length of the
time-interval between each execution.

<script>
var myVar = setInterval(starttime, 1000);

function starttime() {
var d = new Date();
document.write(d.toLocaleTimeString());
}
</script>
clearInterval() method:

The clearInterval() method stops the executions of the function


specified in the setInterval() method.

Syntax:
window.clearInterval(timerVariable)

<p id=“starttime"></p>

<button onclick="clearInterval(stime)">Stop time</button>

<script>
var stime= setInterval(stopWatch, 1000);
function stopWatch() {
var d = new Date();
document.getElementById(“starttime").innerHTML =
d.toLocaleTimeString();
}
</script>
Javascript Object
A javaScript object is an entity having state and behavior (properties
and method).

Creating Objects in JavaScript:


JS Object
Literal By new operator Constructor
JavaScript Object by object literal

Syntax:

object={property1:value1,
property2:value2.....propertyN:valueN}

Var employee=
{
name:“Ram Kumar",
salary:40000
}
document.write(employee.name+" "+employee.salary);
method in JavaScript Object literal

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

<script>
var person = {
firstName: “Sohan",
lastName : “Lal",
};
person.name = function() {
return this.firstName + " " + this.lastName;
};
document.getElementById("demo").innerHTML =“Name is " +
person.name();
</script>
For…in loop
Syntax:

for (variable in object) {


code to be executed
}

The block of code inside of the for...in loop will be executed once for each
property.

<script>
var p;
var person = {fname:“Ram", lname:“Sharma", age:25};

for (x in person) {
p += person[x];
}
Document.write(p);
</script>
By The new Operator
All user-defined objects and built-in objects are descendants of an object
called Object.

Syntax:

var objectname=new Object();

var employee=new Object();


employee.id=101;
employee.name="Ram Sharma";
employee.salary=50000;
document.write(employee.id+" "+employee.name+" "+employee.sa
lary);
Defining method

<script>
var Person = new Object();
Person.id = 1001;
Person[‘n'] = ‘Infoway Technologies’;
Person.getName = function () {
return (Person.n);
}
alert(Person.getName());
</script>
By using an Object constructor
We need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.
The this keyword refers to the current object.

function employee(){
this.name=“Smith”;
this.salary=50000;
}

var e=new employee();


Document.write(e.name+”
“+e.salary);
<p id="demo"></p>
<script>
// Constructor function for Person objects
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.name = function() {
return this.firstName + " " + this.lastName
};
}

// Create a Person object


var p= new Person(“Sohan", “Lal", 50);

// Display full name


document.getElementById("demo").innerHTML = p.name();

</script>
Object Properties
An object is a collection of properties, and a property is an association
between a name (or key) and a value. A property's value can be a function,
in which case the property is known as a method.
syntax
• objectName.property // person.age
• objectName["property"] // person["age“]

<script type="text/javascript">
var Person = new Object();
Person.id = 1001;
Person[‘n'] = ‘Infoway Technologies’;
alert(Person.n);
</script>
Deleting Properties
The delete keyword deletes a property from an object.
The delete keyword deletes both the value of the property and the property itself.

It has no effect on variables or functions.

The delete operator should not be used on predefined JavaScript object


properties.

<script type="text/javascript">
var Person = new Object();
Person.id = 1001;
delete Person.id;
console.log(Person.id);
</script>
JavaScript Object Prototypes
All JavaScript objects inherit properties and methods from a
prototype.

Prototype Inheritance:
The Object.prototype is on the top of the prototype inheritance chain.
Date objects, Array objects, and Person objects inherit from Object.prototype.
Adding Properties and Methods to Objects

Person.prototype.course = “PG-DAC";

Person.prototype.name = function() {
return this.fname + " " + this.lname;
};
document.write(p.name());
Function Expressions
A JavaScript function can also be defined using an expression.

var x = function (a, b) {return a * b}; //anonymous function (a function without a name).
var z = x(4, 3);

Function Hoisting:
myFunction(5);

function myFunction(y) {
return y * y; Functions defined using an expression are not
} hoisted
END
Session-6 & 7
Topics to be covered…
 Introduction to jQuery
 Why we use jQuery
 Ready function
 jQuery Selectors
 jQuery HTML
 jQuery Effects
 jQuery Events
 jQuery Form Validation
 jQuery UI
Introduction to jQuery
jQuery is a lightweight JavaScript library that emphasizes
interaction between JavaScript and HTML

It is cross-platform and supports different types of


browsers

Developed in 2006 by John Resig at Rochester Institute


of Technology
What can jQuery Do
Why jQuery
jQuery is like a pre-packaged set of JavaScript routines that you
may have otherwise needed to write yourself, packaged in an
easy-to-use way.

It uses CSS syntax for selection of element.

jQuery makes animated applications just like Flash

jQuery pages load faster


jQuery vs. JavaScript
Getting started with jQuery

Two ways to access it:


-Download it and reference:

<script src="jquery.js"></script>
(in the same directory)

-Reference the JS file in your HTML (CDN):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js">
</script>
$( document ).ready()
A page can't be manipulated safely until the document is "ready."

jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document
Object Model is ready for JavaScript code to execute.
Basic Selectors
jQuery selectors allow you to select and manipulate HTML element(s).
• TagName
document.getElementsByTagName("tagName");
$("tagName")- $("div"), $("p"), $("div"),.....

• Tag ID
document.getElementById("id");
$("#id") - $("#name"), $("#address")

• Tag Class
document.getElementsByClassName("className");
$(".className") - $(".comment"), $(".code")

• To select all elements - $("*")


Selectors - Combined

$("tagName,.className")
Example: $("h1,.mainTitle")

$("tagName,.className,#tagId")
Example: $("h1,.mainTitle,#firstHeading")
Examples:
$("selector:first") $("p:first")
$("selector:last") $("p:last")
$("selector:odd") $("p:odd")
$("selector:even") $("p:even")
$("selector[attribute]") $("p:[name]")
Condition filters - Form filters
$("selector:visible") $("selector:input")
$("selector:disabled") $("selector:text")
$("selector:enabled") $("selector:password")
$("selector:checked") $("selector:checkbox")
$("selector:button") $("selector:submit")
$("selector:file") $("selector:reset")
:checkbox selector
<script>
$(document).ready(function(){
$("button").click(function(){
$("input:checkbox").each(function(k,v){
alert(k+v+v.value);
}); }); });
</script>
$(document).ready(function(){
$(":checkbox").click(function () {
var x = "";
$("#span1").text("");
$(":checked").each(function (k, v) {
x += v.value;
});
$("#span1").text(x);
})
});
</script>
Retrieve, Set and Remove attributes
Examples:
$("selector").attr("name") $("img").attr("src")
$("selector").attr("key", "val") $("p").attr("class", "source")
$("selector").attr(properties) $("img").attr({ "src" : "/path/",
"title" : "My Img" });
$("selector").removeAttr(attr) $("div").removeAttr("class“ )
Class, HTML, Text, Value - Functions
$("selector").addClass("className")
$("selector").removeClass("className")
$("selector").toggleClass("className")

html() - Sets or returns the content of selected elements (including HTML markup)
$("selector").html()
$("selector").html("html code")

text() - Sets or returns the text content of selected elements


$("selector").text()
$("selector").text("text content")

val() - Sets or returns the value of form fields


$("selector").val()
$("selector").val("value")
<script>
$(document).ready(function () {
$("#button1").click(function () {
alert($("#p1").text());
alert($("#div1").html());
alert($("#text1").val());
});
});
</script>
<script>
$(document).ready(function () {
$("#btn1").click(function(){
$("#p1").text("Hello world!");
});
$("#btn2").click(function(){
$("#p2").html("<b>Welcome</b>");
});
$("#btn3").click(function(){
$(“#text1").val(“Infoway");
});
});
</script>
jQuery Events
Events are a part of the Document Object Model (DOM) and
every HTML element contains a set of events which can trigger
JavaScript Code.
jQuery
Events

Form Keyboard Mouse Browser Document


Events events events events loading

Error Load
Click Resize Ready
Blur Dblclick Scroll Unload
KeyDown
Change Focuout
KeyUp
Focus Hover
KeyPress
Focusin Mousedown
focusout
select Mouseenter
Mouseleave
Mousemove
Mouseout
Mouseover
Mouseup
// Event setup using a convenience method
$( "p" ).click(function() {
console.log( "You clicked a paragraph!" );
});

// Equivalent event setup using the `.on()` method


$("p" ).on( "click", function() {
console.log( "You clicked a paragraph!" );
});
Keydown event
var x = event.which || event.keyCode; //
Use either which or keyCode, depending
on browser support.

<script>
$(document).ready(function () {
$("#text1").keydown(function () {
$("#text2").val(event.which);
});
});
</script>
Focusout event
The focusout event is sent to an element when it, or any element
inside of it, loses focus. Bind an event handler to the "focusout"
event.

<script>
$(document).ready(function () {
$(":text").focusin(function () {
$(this).css("background-color", “red");
});
$(":text").focusout(function () {
$(this).css("background-color", "white");
});
});
</script>
jQuery Effects
The jQuery library provides several techniques for adding animation to
a web page. These include simple, standard animations that are
frequently used, and the ability to craft sophisticated custom effects.
Display Effects - .hide() and .show()
Hide the matched elements. Speed is given in milliseconds; higher values
Show the matched elements indicate slower animations, not faster ones.
The strings 'fast' and 'slow' can be supplied
Syntax: to indicate durations of 200 and 600
$(selector).hide(speed,callback); milliseconds, respectively.

$(selector).show(speed,callback);

jQuery toggle():
Syntax:
$(selector).toggle(speed,callback);
Fading Effects - .fadeIn(), .fadeOut()
Display the matched elements by fading them to opaque.
Hide the matched elements by fading them to transparent.
syntax
$(selector).fadeIn(speed,callback);

$(selector).fadeOut(speed,callback);

Speed is given in milliseconds; higher values indicate slower animations, not


faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of
200 and 600 milliseconds, respectively. If any other string is supplied, or if the
duration parameter is omitted, the default duration of 400 milliseconds is used.
Fading Effects - .fadeTo(), .fadeToggle()
Adjust the opacity of the matched elements.
Display or hide the matched elements by animating their opacity.
opacity: A number between 0
and 1 denoting the target opacity.
Syntax:
$(selector).fadeTo(speed,opacity,callback);
$(selector).fadeToggle(speed,callback);

<script>
$(document).ready(function () {
$("#toggle").on("click", function () {
$("#div1").fadeTo("slow",0.5, function () {
alert("Hello World!");
});
});
});
</script>
Sliding Effects - .slideDown(), .slideUp()
Display the matched elements with a sliding motion.
Hide the matched elements with a sliding motion.

Syntax:
$(selector).slideDown(speed,callback);

$(selector).slideUp(speed,callback);

$(selector).slideToggle(speed,callback);
Stop()
The jQuery stop() method is used to stop animations or effects
before it is finished.

Syntax:
$(selector).stop();
Other Effects - .animate()
Perform a custom animation of a set of CSS properties.
Syntax:
$(selector).animate({params},speed,callback);

By default, all HTML elements have a static position, and cannot be moved.
To manipulate the position, remember to first set the CSS position property
of the element to relative, fixed, or absolute!
JS

HTML $(document).ready(function(){
$(".block").css({
'position': 'absolute',
'backgroundColor': "#abc",
<button id="left">left</button> 'left': '100px',
<button id="right">right</button> 'width': '90px',
<div class="block"></div> 'height': '90px',
'margin': '5px' });
$("#left").click(function(){
$(".block").animate({left: "-=50px"}, "slow");
});
$("#right").click(function(){
$(".block").animate({left: "+=50px"}, "slow");
});
});
jQuery-CSS
These methods get and set CSS-related properties of elements.

Set a CSS Property:


Syntax:
css("propertyname","value");

$("p").css("background-color", "yellow");
jQuery - Add Elements
•append() - Inserts content at the end of the selected elements

•prepend() - Inserts content at the beginning of the selected elements

•after() - Inserts content after the selected elements

•before() - Inserts content before the selected elements

jQuery - Remove Elements


remove() - Removes the selected element (and its child elements)

empty() - Removes the child elements from the selected element


jQuery - Widgets
A jQuery UI widget is a specialized jQuery plug-in.Using plug-in, we can
apply behaviours to the elements.

Autocomplete
Enable to provides the suggestions while you type into the field.

Menu
Menu shows list of items.

Datepicker
It is to open an interactive calendar in a small overlay.

Select menu
Enable a style able select element/elements.

Tooltip
Its provides the tips for the users.

Tabs
It is used to swap between content that is broken into logical sections.
END
Session-8
Topics to be covered…

 What is Node.js
 why Node.js
 What is NPM
 Node.js modules-Built-in and User defined
 Exports keyword
 Node.js Http module
 Node.js File System
 Url Module
 Node.js Events
What is Node.js

Node.js is a cross-platform runtime environment and library for


running JavaScript applications outside the browser. It is used
for creating server-side and networking web applications.

It is open source and free to use.


Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X,
etc.)

Node.js = Runtime Environment + JavaScript Library

•Node.js files contain tasks that will be executed on certain events


•A typical event is someone trying to access a port on the server
•Node.js files have extension ".js"
Features of Node.js
Extremely fast: Node.js is built on Google Chrome's V8 JavaScript
Engine, so its library is very fast in code execution.

I/O is Asynchronous and Event Driven: All APIs of Node.js library


are asynchronous i.e. non-blocking. So a Node.js based server never
waits for an API to return data. The server moves to the next API after
calling it and a notification mechanism of Events of Node.js helps the
server to get a response from the previous API call. It is also a reason
that it is very fast.

Single threaded: Node.js follows a single threaded model with event


looping.

Highly Scalable: Node.js is highly scalable because event mechanism


helps the server to respond in a non-blocking way.

No buffering: Node.js cuts down the overall processing time while


uploading audio and video files. Node.js applications never buffer any
data. These applications simply output the data in chunks.
Modules
A set of function you want to include in your application.

Consider modules to be the same as Javascript libraries.

Modules can either be single file or diectories containing one or


more files
Types of Module

 Bulit In Module

 User Defined Custom Module (Using Exports Object)


How to create Module in Node.js

To create a typical module,you create a file that defines


properties on the exports object with any kind of data,such
a strings,objects and functions.
How to add Module in Node.js

Using require function built-in and custom modules may be


added.

Ex
var http=require(‘http); //Built-In Module

var dt=require(‘./custommodulename’) //custom module


exports
Export Literals:

myModules.js
module.exports = 'Hello world';
//or exports = 'Hello world';

app.js
var msg = require('./myModules.js');
console.log(msg);
exports
Export Object :

myModules.js
exports.Message = 'Hello world';
// or module.exports.Message = 'Hello world';

exports.fn = function (msg) {


console.log(msg);
};
// or module.exports.fn = function (msg) { … };

app.js
var msg = require('./myModules.js');
msg.fn('Hello World');
console.log(msg.Message);
HTTP Module
Node.js has a built-in module called HTTP, which allows Node.js to transfer data over
the Hyper Text Transfer Protocol (HTTP).

Syntax:
var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Hello'); //write a response to the client
res.end(); //end the response
}).listen(1000); //the server object listens on port 1000
URL Module
The URL module splits up a web address into readable parts.

var url = require('url');


var adr = 'http://localhost:1000/default.htm?id=2&name=ram';
var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:1000'


console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?id=2&name=ram'

var qdata = q.query; //returns an object: { id: 2, name: ‘ram' }


console.log(qdata.name); //returns ‘ram'
File System
The Node.js file system module allow you to work with the file system on your computer.

Syntax:
var fs = require('fs');

fs.appendFile()
fs.readFile()
fs.writeFile()
fs.unlink(): delete a file with the File System module
fs.rename()
Events
Node.js allows us to create and handle custom events easily by using events module. Event module includes
EventEmitter class which can be used to raise and handle custom events.

// get the reference of EventEmitter class of events module


var events = require('events');

//create an object of EventEmitter class by using above reference


var em = new events.EventEmitter();

//Subscribe for FirstEvent


em.on('FirstEvent', function (data) {
console.log('First subscriber: ' + data); });

// Raising FirstEvent
em.emit('FirstEvent', 'This is my first Node.js event emitter
example.');
END
Session-9
Topics to be covered…
 Node.js MySQL CRUD Operations
 Node.js MongoDB CRUD Operations
Mysql connect with node.js
npm install mysql --save

MySQL connection
app.js

var mysql = require('mysql');

var con = mysql.createConnection({ // Connection properties


host: “192.168.100.75",
user: “dac38",
port: "3307",
password: “welcome",
database: “dac38"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.end();
});
create table
MySQL create table

var mysql = require('mysql');

var con = mysql.createConnection({ // Connection propertie


host: “192.168.100.75",
user: “dac38",
port: "3307",
password: “welcome",
database: “dac38"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("create table a1 (c1 int, c2 varchar(10), c3 datetime)",
function(err, result) {
if (err) throw err;
console.log("Table created!");
})
con.end();
});
insert record
MySQL insert record

var mysql = require('mysql');

var con = mysql.createConnection({ // Connection properties


host: “192.168.100.75",
user: “dac38",
port: "3307",
password: “welcome",
database: “dac38"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("insert into dept values(1,1,1,1)", function(err, result){
if (err) throw err;
console.log("Record Inserted…");
})
con.end();
});
update record
MySQL update record

var mysql = require('mysql');

var con = mysql.createConnection({ // Connection properties


host: “192.168.100.75",
user: “dac38",
port: "3307",
password: “welcome",
database: “dac38"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("update dept set dname = 'saleel' where deptno=1", function(err,
result){
if (err) throw err;
console.log("Record Updated…");
})
con.end();
});
select
MySQL select record
var mysql = require('mysql');

var con = mysql.createConnection({ // Connection properties


host: “192.168.100.75",
user: “dac38",
port: "3307",
password: “welcome",
database: “dac38"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM emp", function (err, data) {
if (err) throw err;
console.log(data);
});
con.end();
});
select
MySQL select record

var mysql = require('mysql');

var con = mysql.createConnection({ // Connection properties


host: “192.168.100.75",
user: “dac38",
port: "3307",
password: “welcome",
database: “dac38"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM emp where job='manager'", function (err, data) {
if (err) throw err;
console.log(data);
});
con.end();
});
Mongodb connect with node.js
npm install mongodb --save

MongoDB create database:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
console.log("Database created!");
db.close();
});
createCollection

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
var dbo = db.db("mydb");
dbo.createCollection("customers", function(err, res)
{
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
Insert

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res)
{
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});
find

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").findOne({}, function(err, result)
{
if (err) throw err;
console.log(result.name);
db.close();
});
});
Find all

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db)
{
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("customers").find({}).toArray(function(err, result) {{
if (err) throw err;
console.log(result.name);
db.close();
});
});
END

You might also like