Mean Stack
Mean Stack
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).
Light Weighted
Case Sensitive Scripting Language
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");
Lexical Scoping:
Depending on position meaning changes.
Data Types
DataTypes
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
"use strict";
x = 3.14; // This will cause an error because x is not declared
JavaScript Hoisting
<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
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
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 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()
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()
<script>
window.print();
</script>
JavaScript Global Properties & methods
Infinity: A numeric value that represents positive/negative infinity
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”];
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);
Syntax:
array.toString();
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);
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]);
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);
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.
<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):
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])
<script>
var d= new Date();
d.setFullYear(2020, 0, 14);
document.write(d);
</script>
Regular Expressions
Regular Expression Modifiers
Quantifiers
When a webpage loads in the browser. browser creates a DOM for the
page.
Syntax:
document.getElementById(id).innerHTML = new HTML
<script>
document.getElementById("para").innerHTML = "New text!";
</script>
Syntax:
document.getElementById(id).innerText = text
<script>
document.getElementById("para").innerText = "New text!";
</script>
syntax
var node= document.createTextNode(“text”);
<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)
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);
Syntax:
setTimeout(function, milliseconds);
<button onclick="setTimeout(myFunction,
3000)">SetTimeout</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
Window.setInterval() Method
Syntax:
setInterval(function, milliseconds);
<script>
var myVar = setInterval(starttime, 1000);
function starttime() {
var d = new Date();
document.write(d.toLocaleTimeString());
}
</script>
clearInterval() method:
Syntax:
window.clearInterval(timerVariable)
<p id=“starttime"></p>
<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).
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:
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:
<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;
}
</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.
<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
<script src="jquery.js"></script>
(in the same directory)
<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")
$("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")
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!" );
});
<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);
<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.
$("p").css("background-color", "yellow");
jQuery - Add Elements
•append() - Inserts content at the end of the selected 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
Bulit In Module
Ex
var http=require(‘http); //Built-In Module
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';
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');
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.
// 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
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.end();
});
create table
MySQL create table
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
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
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');