0% found this document useful (0 votes)
17 views199 pages

WPT Notes

Uploaded by

mahadwadmayuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views199 pages

WPT Notes

Uploaded by

mahadwadmayuri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 199

Teaching Guidelines for

Web Programming Technologies


PG-DAC September 2021

Duration: 108 hours (48 classroom hours + 48 lab hours + 12 revision/practice hours)

Objective: To introduce the students to HTML, CSS, JavaScript, XML, JSON, Ajax, Node.js, Express.js,
React, React-Redux, and practical relevance of all these technologies.

Evaluation: 100 marks


Weightage: Theory Exam – 40%, Lab exam – 40%, Internals – 20%

Text Books:
 Fundamentals of Web Development, 1e, by Randy Connolly, Ricardo Hoar / Pearson
 MERN Quick Start Guide – Build web applications with MongoDB, Express.js, React, and Node by
Eddy Wilson Iriarte Koroliova / Packt

References:
 Internet & World Wide Web : How to Program by Paul Deitel, Henry Deitel & Abbey Deitel /
Pearson Education
 XML - How to Program by Deitel et al / Pearson Education
 Ajax in Action by Dave Crane, Eric Pascarello / Dreamtech Press
 JavaScript: The Good Parts by Douglas Crockford / O'Reilly
 Pro MERN Stack: Full Stack Web App Development with Mongo, Express, React, and Node by
Vasan Subramanian / Apress
 Web Application Security: A Beginner's Guide by Bryan Sullivan & Vincent Liu / Tata McGraw Hill
 W3Schools Tutorials [ https://www.w3schools.com/ ]
 Mozilla Developer Network Web Development Tutorials [ https://developer.mozilla.org/en-
US/docs/Learn/Getting_started_with_the_web ]
 Curated Tutorial Links on ES6, React, etc. [ https://github.com/markerikson/react-redux-links ]

(Note: Each Session is of 2 hours)

Session 1: Architecture of Web


Lecture:
 Brief history of the Internet
 How does the Internet work?
 Internet Protocol; HTTP
 Domain Names; Domain Name Service servers
 HTTP Protocols
o Difference between HTTP 1.0, HTTP 1.1, and HTTP 2.0
o Methods – GET, POST, HEAD, PUT, DELETE, etc.
o Status codes
o Stateless nature of the protocol and HTTP Session
o HTTPS
 Architecture of the Web
 Web servers – IIS, Apache server

Lab:
 Exploring different browsers
o Mozilla Firefox, Google Chrome, Safari
 Exploring different text editors
o Windows: Notepad++, Linux: Gedit or Vim or Emacs

Session 2: HTML
Lecture:
 Introduction to HTML5
 Introduction to basic HTML Tags
o Alignment, Headings, Anchor, Paragraph, Image, Lists, Tables, and iFrames
 HTML5
o New features in HTML5
o New elements, new attributes, link relations, microdata, ARIA accessibility, objects,
events, and Canvas tags
o HTML5 Validation
o Audio & Video Support
o Geo-location Support
 HTML Forms & Controls
o Input, Text Area, Radio Button, Checkbox, Dropdown, Submit, Reset, Button, etc.
 Introduction to Document Object Model (DOM)
Lab:
 Create a HTML form for building your resume.

Session 3: Cascading Style Sheets (CSS)


Lecture:
 Introduction to CSS, Styling HTML with CSS, Structuring pages with CSS,
 Inline CSS, Internal CSS, External CSS, Multiple styles, CSS Fonts
 CSS Box Model
 id Attribute, class Attribute
 HTML Style Tags
 Linking a style to an HTML document
Lab:
 Apply inline, internal, and external CSS to change colors of certain text portions, bold,
underline, and italics certain words in the previously created HTML resume form.

Session 4: JavaScript
Lecture:
 Introduction to JavaScript
 Variables in JavaScript
 Statements, Operators, Comments, Expressions, and Control Structures
 JavaScript Scopes
 Strings, String Methods
 Numbers, Number Methods
 Boolean Values
 Dates, Date Formats, Date Methods
 Arrays, Array Methods
Lab:
 Practice writing basic JavaScript programs for better understanding of the language constructs
Sessions 5 & 6: JavaScript
Lecture:
 Objects, Object Definitions, Object Properties, Object Methods, Object Prototypes
 Functions, Function Definitions, Function Parameters, Function Invocation, Function Closures
 Introduction to Object Oriented Programming in JS
o Method, Constructor, Inheritance, Encapsulation, Abstraction, Polymorphism
Lab:
 Write a JavaScript program to sort a list of elements by implementing a sorting algorithm.
 Write a JavaScript program to list the properties of a JavaScript object.

Sessions 7 & 8: JavaScript


Lecture:
 Document Object Model (DOM)
o Object hierarchy in JavaScript
o HTML DOM, DOM Elements, DOM Events
o DOM Methods, DOM Manipulation
 Forms, Forms API, Forms Validation
 Regular Expressions
 Errors, Debugging
 Introduction to Browser Dev Tool
 Pushing code quality via JSLint tool
Lab:
 Write a JavaScript function to get First and Last name from the previously created Resume
form
 Validate the entire Resume form using client-side JavaScript
 Write a JavaScript function to validate whether a given value is RegEx or not.

Session 9: jQuery
Lecture:
 Introducing to jQuery
 jQuery selectors
 jQuery events
 jQuery animation effects
 jQuery DOM traversal and manipulation
 Data attributes and templates
 jQuery DOM utility functions
 jQuery plugins
Lab:
 Write a jQuery program to get a single element from a selection of elements of a HTML page.
 You are having sample data for the link. Write jQuery code to change the hyperlink and the
text of an existing link.
 Write a jQuery program to attach a click and double-click events to all <p> elements.
 Write a jQuery program to hide all headings on a page when they are clicked.
o Also find the position of the mouse pointer relative to the left and top edges of the document.

Sessions 10 & 11: JSON & Ajax


Lecture:
 JSON: JavaScript Object Notation (JSON)
o Introduction and need of JSON
o JSON Syntax Rules

o JSON Data - a Name and a Value,


o JSON Objects, JSON Arrays, JSON Files
o JSON parsing
 Ajax
o Introduction to Ajax
o Ajax Framework
o Ajax Architecture
o Web services and Ajax
o Ajax using JSON and jQuery
Lab:
 Create a page showing live score/feed using Ajax and JSON from a live sport/news service end-
point given by the faculty

Session 12: Introduction to Node.js


Lecture:
 Introduction to Node.js
 Browser JS vs. Node.js
 ECMAScript 2015 (ES6)
 Node.js REPL
Lab:
 Install Node.js 12.x.x LTS version on your machine
 Write a recursive function in Node.js
 Write a Node program that prints all the numbers between 1 and 100, each on a separate line.
A few caveats:
o if the number is divisible by 3, print "foo"
o if the number is divisible by 5, print "bar"
o if the number is divisible by both 3 and 5, print "foobar"

Sessions 13 & 14: Node.js Asynchronous Programming


Lecture:
 Introduction to Asynchronous programming and callbacks
 Promises and async & await
 The Event Loop and Timers
Lab:
 Assignment on JavaScript callback functions
 Assignment on Timers, Promises, and Async & Await

Session 15: Node.js Modules


Lecture:
 Understanding Node modules, exports, and require
 Introduction to npm
o package.json and package-lock.json files
o Install, update, and manage package dependencies
o Local and global packages
Lab:
 Create a module and import it in other programs
 Install a module/package using npm

Session 16: Node.js Modules – fs and http


Lecture:
 File I/O – Sync & Async Methods
 HTTP Module – Building an HTTP server
 Developing a Node web application
Lab:
 Write a program to create a new file and write some content to it in synchronous mode and
read and display file contents on standard output in async mode
 Build a simple Node.js web application serving both HTTP GET and POST methods

Session 17: Introduction to Express


Lecture:
 Introduction to Express
 Getting started with Express
 Application, Request and Response Objects
 Routes and Middlewares
 Templates, Template Engines, and Rendering Views
Lab:
 Use Node and Express to write a simple web application that consists of at least 5 route
implementations
 Rebuild any previous Node assignment using Express and a template engine

Session 18: Introduction to React


Lecture:
 Introduction to React
 Getting started with React
 React Elements and React Components
 Function and Class Components
 Working with React Components and Props
o Compose components
o Render components
o Declutter components
Lab:
 Rebuild any previous plain HTML lab assignment using React
 Build a React Clock app showing time (hh:mm:ss) of any three countries

Sessions 19 & 20: React


Lecture:
 Introduction to State and Lifecycle
 Stateful components and lifecycle methods
 Props vs. State vs. Context
 Handling events
 Conditional rendering
Lab:
 Implement the following items in the React Clock app
o Update the time (hh:mm:ss) using State and Lifecycle methods
o Add a close function on each rendered clock component
o Assign background color of rendered clock components based on AM, PM

Session 21: React


Lecture:
 Lists and Keys
o Rendering Multiple Components

o Basic List Component


 Working with forms and inputs
 Refs and the DOM
 Lifting state up
Lab:
 Implement and integrate a new feature in the React Clock app where one can select a country
time zone from dropdown list and click on “Add” button to render it.

Session 22: React


Lecture:
 Error Boundaries
 Composition vs. Inheritance
o Containment
o Specialization
 Thinking in React
Lab:
 Implement error boundaries at appropriate places in the React Clock app

Session 23: Introduction to React-Redux


Lecture:
 Introduction to Redux
 Actions, Reducers, and Stores
 Usage with React
Lab:
 Make necessary changes in the design and implementation of React Clock app using React-
Redux to maintain the application state.

Session 24: Responsive Web Design & Web Security


Lecture:
 Introduction of UI Scripting
 The Best Experience for All Users
o Desktop, Tablet, Mobile
 Bootstrap
o Overview of Bootstrap, Need to use Bootstrap
o Bootstrap Grid System, Grid Classes, Basic Structure of a Bootstrap Grid
o Typography
o Components – Tables, Images, Jumbotron, Wells, Alerts, Buttons, Button Groups,
Badges/Labels, Progress Bars, Pagination, List Groups, Panels, Dropdowns, Collapse,
Tabs/Pills, Navbar
o Forms, Inputs
o Bootstrap Themes, Templates
 Web Security
o Introduction to Web security
o SQL Injection, Cross-Site Scripting (XSS)
o JSON and Security Concerns, Cross Site Request Forgery (CSRF), Injection Attacks
o Security Standards (OWASP)
Lab:
 Update the design of the Resume form using Bootstrap
HTML

What is HTML?
• HTML(Hyper Text Markup Language)
 is a language for describing web pages.
 not a programming language
 uses markup tags to describe web pages.
• Most Web documents are created using HTML.
 Documents are saved with extension .html or .htm.
• Markup?
 Markup Tags are strings in the language surrounded by a < and a > sign.
 Opening tag: <html> Ending tag: </html>
 Not case sensitive.
 Can have attributes which provide additional information about HTML elements on
your page. Example
o <body bgcolor="red">
o <table border="0">
3

HTML
• An HTML document appears as follows:
<!DOCTYPE HTML>
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>

 HTML Head Section: contain information about the document. The browser does not
display this information to the user. Following tags can be in the head section:
<base>, <link>, <meta>, <script>, <style>, and <title>.
 HTML Body Section: defines the document’s body. Contains all the contents of the
document (like text, images, colors, graphics, etc.).

HTML Body Section


• <body> Element:
 Each document can have at most one <body> element.
 Attributes used in <body> element are:
o BGCOLOR: Gives a background color to HTML page.
o BACKGROUND: Use to specify images to the BACKGROUND.
o TEXT: Specifies text color throughout the browser window
o LINK, ALINK, VLINK: Used to specify link color, active link color & visited link color
 Examples:
o <body text=“red”> OR <body text=“#FF0000”>
o <body link=“red” alink=“blue” vlink=“purple”>
o <body bgcolor=“black”> OR <body bgcolor=“#000000”>
o <body background=“http://www.mysite.edu/img1.gif”>
o <body background=“symbol.gif” text=“red” link=“blue” bgproperties=“fixed”>

<HTML>
<HEAD>
<TITLE>Body Tag</TITLE>
</HEAD>
<BODY BGCOLOR="pink" text="red"
alink="green" link="yellow">
<a href="body.html">background</a>
color of the page is pink. and text color is red
</BODY>
</HTML>
5

Physical Character Effects


• Bold Font: <b>…</b>
• Italic: <i>…</i>
• Underline: <u>…</u>
• Strikethrough: <strike> or <s>
• Fixed width font: <tt> - normal text in fixed-width font
• Subscript: <sub>
• Superscript: <sup>

<html>
<body>
<b>This is in bold font</b>
<i>This text is in Italics</i>
<u>This text is Underlined</u>
<small>This is small text.</small>
<font size=7>This text is very large</font>
<font color=”Blue”>This is Blue Text.</font>
<strike>This is strikethrough style text</strike>
The chemical formula of water is h<sub>2</sub>o.
A simple formula for a parabola is y = x<sup>2</sup>.
</body>
</html>

Document (Body) Contents


• Body Text
 HTML truncates spaces in your text.
 Use <br> to insert new lines.
 Use <p> tag to create paragraphs.
 Use <div> to hold division or a section in an HTML document
 Use <span> as an inline container to mark up a part of a text, or a part of a
document

• Comments in HTML Document


 Increase code readability; Ignored by the browser.
 Example of HTML comment: <!-- This is a Sample HTML Comment -->
7

Logical Character Effects


• Heading Styles:
 <hn>…………</hn>
o Value of n can range from 1 to 6
 <h1 align=“center”>This is level 1 heading</h1>

Using Heading styles

<html>
<head><title>This is the first html page</title>
<body>This is the first html page created
<h1 align=”left”>This is level 1 heading</h1>
<h2 align=”right”>This is level 2 heading</h2>
<h3 align=”center”>This is level 3 heading</h3>
</body>
</head>
</html>

Horizontal Lines in a Web Page


• <hr> - horixontal Rule. Attributes:
 Size: Line thickness <hr size=“5”>
 Width: Line width either in pixels or % of browser window
o <hr width=“100”> or <hr width=“60%”>
 Align: Alignment values can be left, center or right <hr align=“center”>
 Color: to display colored horizontal lines. Eg <hr color=“red”>

<body> <p>
This paragraph contains a lot of lines
in the source code,
but the browser ignores it. </p>
<hr size="2" width="50%" color="blue“ align = “left” > <p>
Notice the horizontal rule occupying 50 % of the window width.
</p> This paragraph contains <br> line breaks in the
source code <br> so this is the third line displayed within the paragraph.
</body>
9

Numbered List (Ordered List)


• Automatically generate numbers in front of each item in the list
 Number placed against an item depends on the location of the item in the list.
 Example:
<body>
<ol>
<li>INDIA</li>
<li>SRILANKA</li>
</ol>
</body>

 To start an ordered list at a number other than 1, use START attribute:


Example : <ol start=11>

• Select the type of numbering system with the type attribute. Example:
o A-Uppercase letters. <OL TYPE=A>
o a-Lowercase letters. <OL TYPE=a>
o I-Uppercase Roman letters
o i-Lowercase Roman letters
o 1-Standard numbers, default

10

Bulleted List (Unordered List)


• Example: <ul>
<li>Latte</li>
<li>Expresso</li>
<li>Mocha</li>
</ul>

• To change the type of bullet used throughout the list, place the TYPE attribute
in the <UL> tag at the beginning of the list.
 DISC (default) gives bullet in disc form.
 SQUARE gives bullet in square form.
 CIRCLE gives bullet in circle form.

<ul>
<li type=‘disc’>Latte</li>
<li type=‘square’>Expresso</li>
<li type=‘circle’>Mocha</li>
</ul>
11

Adding Image
• Images are added into a document using <img> tag.
• Attributes of <img> tag are:
 alt: Alternative text to display for non-graphical browsers.
 align: Image horizontal alignment. Valid values: left, right, center.
 width/Height: Sets the width and height of the image.
 src: Specifies the image path or source.

<IMG src="home.png“ height="100“ width="200" >

12

Table
• Use <table> tag to create a table.
• Table Attributes:
 Border: <table border=“2”>………</table>
 Align: defines the horizontal alignment of the table element.
o Values of the align attribute are right, left and center. <table align=“center”>
 Width: defines the width of the table element.
o <table width=“75%”>………</table>
o <table width=“400”>………</table>
• Example:
<table border="1">
<tr border="1">
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>
13

Table Data

• An HTML table has two kinds of cells:


 Header Cells <th>: Contain header information (created with <th> element) ; The text is
bold and centered.
 Standard Cells <td>: Contain data (created with the td element) ; The text is regular and
left-aligned.
<table>
<tr> <th>Column1 Header</th> <th>Column2 Header</th></tr>
<tr> <td>Cell 1,1</td> <td>Cell 1,2</td> </tr>
<tr> <td>Cell 2,1</td> <td>Cell 2,2</td> </tr>
</table>

• You can insert a bgcolor attribute in a <table>, <td>, <th> or <tr> tag to set the
color of the particular element.
<table bgcolor="cyan">
<tr bgcolor="blue">

<table bgcolor="cyan">
<tr bgcolor="blue">
<th bgcolor="red">Header 1</th> <th>Header 2</th>
</tr>
<tr> <td bgcolor="green">data 1</td> <td>data 2</td> </tr>
</table>

14

How Does a Hyperlink Work?

• Hyperlinks access resources on the internet.


• Create a link with <a href=“”> (anchor)

 <a href="http://www.mysite.com/login.htm">Login Here</a>


 Hello, Welcome to <a href="welcome.htm">My Site</a>
 I have some <a href="http://www.state.edu/info/info.htm">
older information</a> about this subject.

• Hyperlinks in Lists Items & Table Elements

<ul>
<li><a href=home.html>mumbai</a></li>
<li><a href=home.html>pune</a></li>
<li><a href=home.html>nasik</a></li>
</ul>

<table border=1>
<tr><th>team<th>points<th>grade</tr>
<tr><td><a href=home.html>mumbai</a></td><td>90</td><td>a</td></tr>
<tr><td><a href=home.html>pune</a></td><td>86</td><td>b</td></tr>
<tr><td><a href=home.html>nasik</a></td><td>80</td><td>c</td></tr>
</table>
15

HTML Forms : Types of Form Fields

<form method=“get/post” action=“URL”>


Field definitions
</form>
• <input> tag is used to create form input fields.
 Type attribute of <input> tag specifies the field type
o Single line text box <input type=“text”>
o Password field <input type=“password”>
o Hidden field <input type=“hidden”>
o Radio button <input type=“radio”>
o Checkbox <input type=“checkbox”>
o File selector dialog box <input type=“file”>
o Button <input type=“button”>
o Submit/Reset <input type=“submit/reset”>
• <textarea>
• <select>
• <button>

16

Text Field
• Single Line Text Fields: used to type letters, numbers, etc. in a form.
<INPUT TYPE=”type” NAME=”name” SIZE=”number” VALUE=”value” maxlength=n>
 Eg:
<form>
First name: <input type="text" name="firstname“ value=“fname>
Last name:<input type="text" name="lname">
</form>

• Text Area (Multiple Line Text Field)


 A text area can hold an unlimited number of characters. Text renders in a fixed-width font
(usually Courier).
 You can specify text area size with cols and rows attributes.
<textarea name=“name” rows=“10” cols=“50” [disabled] [readonly]>
Default-Text
</textarea>

<textarea name=“address” rows=5 cols=10>


Please write your address
</textarea>
<textarea rows=“4” cols=“20”>
17

Check Box

• Lets you select one or more options from a limited number of choices.
<input type=“checkbox” name=“name” value=“value” [checked] [disabled]> Checkbox
Label
 Content of value attribute is sent to the form's action URL.

<input type=“checkbox” name=“color1” value=“0”/>Red


<input type=“checkbox” name=“color3” value=“1” checked/>Green

Radio Buttons
<input type=“radio” name=“name” value=“value” [checked] [disabled]> Radio Button Label
• Content of the value attribute is sent to the form's action URL.
<form>
<input type="radio" name="sex" value="male"/>Male<br>
<input type="radio" name="sex" value="female"/> Female
</form>

Hidden Field
• Allows to pass information between forms:
• <input type=“hidden” name=“name” size=“n” value=“value”/>
• <input type=“hidden” name=“valid_user” size=“5” value=“yes”/>

18

Password Fields
• <input type=“password” name=“name” size=n value=“value” [disabled]>
 Eg: Enter the password:<input type=“password” name=“passwd” size=20 value=“abc”>

File Selector Dialog Box


• <input type=“file” name=“name” size=“width of field” value=“value”>

<FORM>
Please select file that you want to upload:
<INPUT name=“file” type=“file”> <BR>
<INPUT type=“submit” >
</FORM>

Action Buttons
• To add a button to a form use:
• <input type=“button” name=“btnCalculate” value=“Calculate”/>
• To submit the contents of the form use:
• <input type=“submit” name=“btnSubmit” value=“Submit”/>
• To reset the field contents use:
• <input type=“reset” name=“btnReset” value=“Reset”/>
19

Drop-Down List
<select name=“name” multiple=“true/false” size=n [disabled]>
<option [selected] [disabled] [value]>Option 1</option>…
</select>
 Multiple: States if multiple element selection is allowed.
 Size: Number of visible elements.
 Disabled: States if the option is to be disabled after it first loads.
Eg:

<form>
<select multiple size="3" name="pref">
<option value="ih" selected>Internet-HTML</option>
<option value="js">Javascript</option>
<option value="vbs">VBscript</option>
<option value="as">ASP</option>
<option value="xm">XML</option>
<option value="jv">JAVA</option>
<option value="jsp">jsp</option>
</select>
</form>

<html><head><title>form examples</title></head>
<body bgcolor="pink">
<form name="form1" action="store.html" method="post">
Complete example
<p>
<strong>Enter first name</strong>: <input name="username">&nbsp;&nbsp;&nbsp;&nbsp;
<strong>Enter lastname</strong>: &nbsp; <input maxlength="30" name="surname"></p>
<p><strong>Enter&nbsp; address:</strong>&nbsp;&nbsp;&nbsp;&nbsp;
<textarea name="addr" rows="3" readonly value="sjdshd"></textarea>
<br><br>
<strong>Select the training programs attended:</strong>
<input type="checkbox" value="internet/html" name="internet-html"> Internet/HTML
<input type="checkbox" checked value="c programming" name="c-programming">C Programming
<input type="checkbox" value="dbms-sql" name="dbms-sql"> DBMS-SQL </p>
<p><strong>Select the stream you belong to:</strong>
<input type="radio" value="science" name="s-grp"> Science
<input type="radio" value="arts" name="s-grp"> Arts
<input type="radio" value="commerce" name="s-grp"> Commerce
<input type="radio" value="oth2" name="s-grp">Engineering </p>
<strong>Which training program would you like to attend ?</strong>
<select size="5" multiple name="pref">
<option value="ih" selected>Internet-HTML
<option value="js">Javascript
<option value="vbs">VBscript
<option value="as">ASP
<option value="xm">XML
<option value="jv">JAVA
<option value="jsp">jsp</option>
</select> <br>
<input type="button" value="exit" name="but">
<input type="submit" value="save">
<input type="reset" value="reset">
</form></body></html>
HTML5

What's new in HTML5?

• HTML5 offers new enhanced set of tags


 New Content Tags : <nav>,<section>,<header>,<article>,<aside>,<summary>
 New Media Tags : <video>,<audio>
 New Dynamic drawing : <canvas>graphic tag
 New form controls, like calendar, date, time, email, url, search

• Support for JavaScript APIs


 Canvas element for 2D drawing API
 Video and audio APIs
 APIs to support offline storages
 The Drag & Drop APIs
 The Geolocation API
 Web workers, WebSQL etc
HTML5 Attributes for <input>
• A Form is one of the most basic and essential feature of any web site
 HTML5 brings 13 new input types
 HTML5 introduces these data types via the <input type=”_NEW_TYPE_HERE_”/>
format

• Placeholder - A placeholder is a textbox that hold a text in lighter shade


when there is no value and not focused
 <input id="first_name" placeholder=“This is a placeholder">
 Once the textbox gets focus, the text goes off and you shall input your own text

• AutoFocus - Autofocus is a Boolean attribute of form field that make browser


set focus on it when a page is loaded
 <input id ="Text2" type="text" autofocus/>

• Required - A "Required Field" is a field that must be filled in with value before
submission of a form
• <input name="name" type="text" required />

New Form elements

• Email - This field is used to check whether the string entered by the user is valid
email id or not.
 <input id="email" name="email" type="email" />

• Search - used for search fields (behaves like a regular text field).
 <input id="mysearch" type="search" />

• Tel - used for input fields that should contain a telephone number.
 <input type="tel" name="usrtel">
• url - is used for input fields that should contain a URL address.
 Depending on browser support, the url field can be automatically validated when
submitted.
• color – displays a color palette
New Form elements

• Number - used for input fields that should contain a numeric value.
 Min and max parameters provided to limit the values.
 Browser will treat it as simple textfield if it doesn’t support this type.
 <input id="movie" type="number" value="0"/>
 <input type="number“ min="0“ max="50“ step="2“ value="6">

• Range - used for input fields that should contain a value within a range
 Browser will treat it as simple textfield if it doesn’t support this type
 <input id="test" type="range"/>
 <input type="range" min="1" max="20" value="0">

New Form elements

• Date - used for input fields that should contain a date.


 Depending on browser support, a date picker can show up in the input field.
 <input id="meeting" type="date“ />

• month - Selects month and year


• week - Selects week and year
• time - Selects time (hour and minute)
• datetime - Selects time, date, month and year
• datetime-local - Selects time, date, month and
year (local time)
New Form elements
• Data List - specifies a list of options for an input field. The list is created with
option elements inside the datalist.
 seems like type-ahead auto suggest textbox as you can see in Google search box

<input id="country_name"
name="country_name"
type="text“
list="country" />

<datalist id="country">
<option value="Australia">
<option value="Austria">
<option value="Algeria">
<option value="Andorra">
<option value="Angola">
</datalist>

Audio
• Until now, there has never been a standard for playing audio on a web page.
 Today, most audio is played through a audio plugin (like Microsoft Windows Media
player, Microsoft Silverlight ,Apple QuickTime and the famous Adobe Flash).
 However, not all browsers have the same plugins.
 HTML5 specifies a standard way to include audio, with the audio element; The audio
element can play sound files, or an audio stream.
 Currently, there are 3 supported formats for the audio element: Ogg Vorbis, MP3,
.webm and WAV
 Other properties like auto play, loop, preload area also available

<audio controls>
<source src="vincent.mp3" type="audio/mpeg"/>
<source src="vincent.ogg" type="audio/ogg"/>
</audio>
Video
• Until now, there hasn't been a standard for showing video on a web page.
 Today, most videos are shown through a plugin (like Flash). However, not all
browsers have the same plugins.
 HTML5 specifies a standard way to include video with the video element
 Supported video formats for the video element : Ogg, MP4, WebM, .flv, .avi
 Attributes : width, height, poster, autoplay, controls, loop, src

<video controls="controls" width="640" height="480" src=“bunny.mp4" />


Your browser does not support the video element.
</video>

Canvas
• A canvas is a rectangle in your web page within which you can use
JavaScript to draw shapes
 Canvas can be used to represent something visually in your browser like Simple
Diagrams, Fancy user interfaces, Animations, Charts and graphs, Embedded
drawing applications, Working around CSS limitations
 The canvas element has several methods for drawing paths, boxes, circles,
characters, and adding images.
 The canvas element has no drawing abilities of its own. All drawing must be done
inside a JavaScript

<canvas id="myCanvas" width="200" height="100">


</canvas>

<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas=document.getElementById('myCanvas');
var ctx=canvas.getContext('2d');
ctx.fillStyle='#FF0000';
ctx.fillRect(0,0,80,100);
</script>
New Semantic Elements

• <section> : can be used to thematically group content, typically with a heading.

• <article>: element represents a self-contained composition in a document, page,


application, or site that is intended to be independently distributable or reusable
 Eg a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment
• <nav>: Represents a major navigation block. It groups links to other pages or to
parts of the current page.
• <Header>: tag specifies a header for a document or section. Can also be used as a
heading of an blog entry or news article as every article has its title and published
date and time

New Semantic Elements


• <aside>: The "aside" element is a section that somehow related to main
content, but it can be separate from that content header and footer element in
an article.
• <footer>: Similarly to "header" element, "footer" element is often referred to
the footer of a web page.
 However, you can have a footer in every section, or every article too

• <figure>: The <figure> tag specifies self-contained


content, like illustrations, diagrams, photos, code
listings, etc.
 This element can optionally contain a figcaption
element to denote a caption for the figure.

Fat footer on
the w3c site
33

What is CSS?
• Cascading Styles Sheets - a way to style and present HTML.
 HTML deals with content and structure, stylesheet deals with formatting and
presentation of that document.
 Allows to control the style and layout of multiple Web pages all at once.
• Example:
Messy HTML
<font color="#FF0000" face="Verdana, Arial, Helvetica, sans-serif">
<strong>This is text</strong></font>

<p class=“MyStyle”>My CSS styled text</p>


…………….
<style>
.myStyle {
font-family: Verdana, Arial, Helvetica, sans-serif; font-weight: bold; color: #FF0000; }
</style>

• Why CSS?
 saves time
 Pages load faster
 Easy maintenance
 Superior styles to HTML

34

CSS Syntax
• A CSS rule has two parts: a selector, and one or more declarations:

• "HTML tag" { "CSS Property" : "Value" ; }


Selects all the paragraphs in HTML
document and gives them style
35

Three Ways to Insert CSS


• Embedded Style Sheets
 Style defined between <STYLE>..</STYLE> tags. <STYLE> tags appear either in
<HEAD> section or between </HEAD> and <BODY> tags.
 Example in previous slide

• Linked Style Sheets


 Separate files (extn .CSS) that are linked to a page with the <LINK> tag. Are
referenced with a URL. Placing a single <LINK> tag within the <HEAD> tags links the
page that needs these styles.
 <head> <link rel="stylesheet" type="text/css" href="mystyle.css"> </head>

• Inline Style Sheets


 Only applies to the tag contents that contain it. Used to control a single tag element.
Tag inherits style from its parent. Egs.
 <p style="color:sienna;margin-left:20px">This is a paragraph.</p>
 <p style="background: blue; color: white;">A new background and font color with inline
CSS</p>

36

Demo: Link Style Sheet


<html> body { background: black;
<head> color:green
<link rel=stylesheet href=“linked_ex.css” }
type=“text/css”> h1 { background: orange;
</head> font-family: Arial, Impact;
<body> color: blue;
<h2>This is Level 2 Heading, with style</h2> font-size:30pt;
<h1>This is Level 1 Heading, with style</h1> text-align: center
<h3>This is Level 3 Heading, with style</h3> }
<h4>This is Level 4 Heading, without style</h4> h2, h3 { background: gold;
</body> font-family: Arial, Impact;
</html> color:red }

linked_ex2.css
37

Inline Style Sheet


• All style attribute are specified in the tag it self. It gives desired effect on that
tag only. Doesn’t affect any other HTML tag.

<body style="background: white; color:green">


<h2 style="background: gold; font-family: Arial, Impact; color:red">
This is Level 2 Heading, with style</h2>
<h1 style="background: orange; font-family: Arial, Impact; color: blue;font-size:30pt; text-
align: center">This is Level 1 Heading, with style</h1>
<h3 style="background: gold; font-family: Arial, Impact;color:red">
This is Level 3 Heading, with style</h3>
<h4>This is Level 4 Heading, without style</h4>
<h1>This is again Level 1 heading with default styles</h1>
</body>

Types of selectors
• HTML selectors
 Used to define styles associated to HTML tags. – already seen!!!!
• Class selectors
 Used to define styles that can be used without redefining plain HTML tags.
• ID selectors
 Used to define styles relating to objects with a unique id
ID Selector & Style Sheet Classes
<style>
H1.myClass {color: blue}
.myOtherClass { color: red; text-align:center}
</style>
<body style="background: white; color:green">
<H1 class="myClass">This text would be blue</H1>
<p class="myOtherClass">The text would be in red</P>
<html> <head> <H3 class="myOtherClass">This is level 2 heading</H3>
<style> <table class=myotherClass border width=100%>
#para1 { <td>Data 1</td><td>Data 2</td></table>
text-align:center; <h3>This is Level 4 Heading, without style</h3>
color:red; <h1>This is again Level 1 heading with default styles</h1>
}
</style> </head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the
style.</p>
</body>
</html>

CSS Box Model


• All HTML elements can be considered as boxes.
• The CSS box model is essentially a box that wraps around HTML elements, and it
consists of:
 Margin - Clears an area around the border. The margin does not have a background color,
it is completely transparent
 Border - A border that goes around the padding and content. The border is affected by the
background color of the box
 Padding - Clears an area around the content. The padding is affected by the background
color of the box
 Content - The content of the box,
where text and images appear
CSS Border
• The border property is a shorthand for the following individual border properties:
border-width, border-style (required), border-color

p { border: 5px solid red; }

CSS Styling
Lesson 10. Cascading Style Sheets
CSS Background
• CSS background properties are used to define the background effects of an
element.
• CSS properties used for background effects:

background-color Sets the background color of an element


background-image Sets the background image for an element
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated

With CSS, a color is specified by:


• Example: • a HEX value - like "#ff0000"
 div {background-color:#b0c4de;} • an RGB value - like "rgb(255,0,0)"
• a color name - like "red"
 body {background-image:url('paper.gif');}
 body {background-image:url('gradient2.png');background-repeat:repeat-x;}
 body {background-image:url('img_tree.png'); background-repeat:no-repeat;
background-position:right top; }

• The background-repeat property sets if/how a background image will be repeated.


 By default, (repeat) : a background-image is repeated both vertically and horizontally.
 no-repeat : The background-image is not repeated. The image will only be shown once

Demo : CSS Background


body {
background-image: url("img_tree.gif"), url("img_flwr.gif");
background-color: #cccccc;
}

body {
background: #00ff00 url("smiley.gif") no-repeat fixed center;
}

<html>
<head><style>
body {
background-image:url('img_tree.png');
background-repeat:no-repeat;
background-position:right top;
margin-right:200px;
}
</style> </head>
<body>
<h1>Hello World!</h1>
<p>Background no-repeat, set position example.</p>
<p>Now the background image is only shown once, and positioned away from the text.</p>
<p>In this example we have also added a margin on the right side, so the background image will never
disturb the text.</p>
</body></html>
CSS Text
• CSS Text Properties

color Sets the color of text


direction Specifies the text direction/writing direction
letter-spacing Increases or decreases the space between characters in a text
text-align Specifies the horizontal alignment of text
text-decoration Specifies the decoration added to text
text-indent Specifies the indentation of the first line in a text-block
text-shadow Specifies the shadow effect added to text
text-transform Controls the capitalization of text
white-space Specifies how white-space inside an element is handled
word-spacing Increases or decreases the space between words in a text

<style>
h1 {text-decoration:overline;}
h2 {text-decoration:line-through;}
h3 {text-decoration:underline;}
</style>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>

Demo : <style>
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
</style>
<body>
<p class="uppercase">This is some text.</p>
<p class="lowercase">This is some text.</p>
<p class="capitalize">This is some text.</p>
</body>

<head> <style>
h1 {text-align:center;color:#00ff00;}
p.date {text-align:right;}
p.main {text-align:justify;}
p.ex {color:rgb(0,0,255);}
p.indent {text-indent:50px;}
</style> </head>
<body>
<h1>Hello World!</h1>
<p class="date"> Sep 2013</p>
<p class="main indent">The CSS property text-align corresponds to the attribute align used in old versions of
HTML. Text can either be aligned to the left, to the right or centred. In addition to this, the value justify will
stretch each line so that both the right and left margins are straight. You know this layout from for example
newspapers and magazines. </p>
<p class="ex">The property text-decoration makes it is possible to add different "decorations" or "effects" to
text. </p>
</body>
More examples
• P { word-spacing:30px; }

• h1 {text-shadow:2px 2px #FF0000;}

• p.small {line-height:70%;}
• p.big {line-height:200%;}

• h1 {letter-spacing:2px;}
• h2 {letter-spacing:-3px;}

CSS : Styling Fonts


• CSS font properties define the font family, boldness, size, and the style of a
text.

font-family Specifies the font family for text


font-size Specifies the font size of text
font-style Specifies the font style for text
font-variant Specifies if a text should be displayed in a small-caps font
font-weight Specifies the weight of a font

• Example:
 p.normal {font-weight:normal;}
 p{font-family:"Times New Roman", Times;}
 p.italic {font-style:italic;}
 h1 {font-size:40px;}
 p.small { font-variant:small-caps; }
Styling lists
• The CSS list properties allow you to: Example:
 Set different list item markers for ordered lists ul.circle {list-style-type:circle}
ol.upper-roman {list-style-type:upper-roman}
 Set different list item markers for unordered lists ul { list-style-image: url('sqpurple.gif'); }
 Set an image as the list item marker
• CSS List Properties
list-style-image Specifies an image as the list-item marker
list-style-position Should the list-item markers appear inside or outside the content flow
list-style-type Specifies the type of list-item marker

<html>
<head>
<style> Image and table
ul { list-style-image:url('sqpurple.gif’); }
</style> img {
</head> float: right;
<body> margin: 0 0 10px 10px;
<ul> }
<li>Coffee</li>
<li>Tea</li> table{
<li>Coca Cola</li> border: 1px solid black;
</ul> border-collapse: collapse;
</body> }

CSS Box Model


• The CSS box model is essentially a box that wraps around HTML elements; it
consists of:
 Margin - Clears an area around the border. The margin does not have a background color,
it is completely transparent
 Border - A border that goes around the padding and content. The border is affected by the
background color of the box
 Padding - Clears an area around the content; padding is affected by the background color
of the box
 Content - The content of the box, where text and images appear

• Padding defines the inner distance of elements to the end of the box.
• Example
 padding-top:25px; <head><style>
padding-bottom:25px; p { background-color:yellow; }
padding-right:50px; p.padding {
padding-left:50px; padding:25px 25px 50px 50px;
}
</style></head>
<body>
<p>This is a paragraph with no specified padding.</p>
<p class="padding">This is a paragraph with specified paddings.</p>
</body>
Margins
• Margins allow you to put a bigger distance between your elements
 the margin is an outer, invisible border around your element.
<style type="text/css">
You can define the margins for a
.box {
box individually or combine them
background-color: DarkSeaGreen;
into one statement.
width: 100px;
height: 100px;
.box { ….; margin: 10px 10px 10px 10px; }
margin-top: 10px;
margin-right: 5px;
margin-bottom: 10px;
margin-left: 5px;
}
</style>
<div class="box"> Box </div>

<head>
<style>
p.ex1 {margin:2cm 4cm 3cm 4cm}
</style>
</head>
<body>
<p>A paragraph with no specified margins.</p>
<p class="ex1">A paragraph with specified margins.</p>
<p>A paragraph with no specified margins.</p>
</body>

CSS Border
• The border property is a shorthand for the following individual border
properties: border-width, border-style (required), border-color
<style type="text/css">
.box {
width: 100px;
height: 100px;
border-color: Blue;
border-width: 2px;
border-style: solid;
} p { border: 5px solid red; }
</style>
<div class="box">
Hello, world!
</div>

<div class="box" style="border-style: dashed;">Dashed</div>


<div class="box" style="border-style: dotted;">Dotted</div>
<div class="box" style="border-style: double;">Double</div>
<div class="box" style="border-style: groove;">Groove</div>
<div class="box" style="border-style: inset;">Inset</div>
<div class="box" style="border-style: outset;">Outset</div>
<div class="box" style="border-style: ridge;">Ridge</div>
<div class="box" style="border-style: solid;">Solid</div>
CSS3 border
• CSS 3 defines “border radius”, giving developers the possibility to make
rounded corners on their elements.

<style> #rcorners3 {
#rcorners1 { border-radius: 25px;
border-radius: 25px; background: url(paper.gif);
background: #8AC007; background-position: left top;
padding: 20px; background-repeat: repeat;
width: 100px; padding: 20px;
height: 100px; width: 100px;
} height: 100px;
#rcorners2 { }
border-radius: 25px; </style>
border: 2px solid #8AC007; <p id="rcorners1">Rounded corners!</p>
padding: 20px; <p id="rcorners2">Rounded corners!</p>
width: 100px; <p id="rcorners3">Rounded corners!</p>
height: 100px;
}

border-radius: 100px 100px 0 0;

Shadow Effects
• You can add shadow to text and to elements.
 text-shadow property applies shadow to text.
 box-shadow property applies shadow to elements.

<style>
.c1{text-shadow: 2px 2px;}
.c2{text-shadow: 2px 2px red;}
.c3{text-shadow: 2px 2px 5px red;}
.c4{color: white; text-shadow: 2px 2px 4px #000000;}
</style>
<p class="c1">para-1</p>
<p class="c2">para-2</p>
<p class="c3">para-3</p>
<style>
<p class="c4">para-4</p>
.c1{box-shadow: 10px 10px;}
.c2{box-shadow: 10px 10px grey;}
.c3{ box-shadow: 10px 10px 5px grey;}
p { width: 300px; height: 100px; padding: 15px; background-color:
yellow; }
</style>
<p class="c1">para-1</p>
<p class="c2">para-2</p>
<p class="c3">para-3</p>
Javascript

Overview
• JavaScript is Netscape's cross-platform, object-based scripting language
 JavaScript code is embedded into HTML pages
 It is a lightweight programming language
 Client-side JavaScript extends the core language by supplying objects to control a
browser and its Document Object Model
• Why use Javascript?
 Provides HTML designers a programming tool :
 Puts dynamic text into an HTML page
 Reacts to events
 Reads and writes to HTML elements :
 Can be used to perform Client side validation

<html>
 The <SCRIPT> tag <head> </head>
<body>
<SCRIPT> <script type="text/javascript">
JavaScript statements … document.write("<H1>Hello World!</H1>");
</SCRIPT> alert(“some message”);
console.log(“some message”);
</script>
</body></html>
Embedding JavaScript in HTML
<html>
• Where to Write JavaScript?
<head>
 Head Section <script type="text/javascript">
 Body Section function message() {
alert(“Hello World")
 External File }
</script>
<html> </head>
<head></head> <body onload="message()">
<body > </body>
<script language=“javascript"> </html>
document.write(“Hello World!“)
</script>
</body>
</html>

<head>
<script src="common.js">
<!– no javascript statements  //common.js file contents
</ script> var msg
</head> msg=“<h1>in external file</h1>"
<body>
<script>
document.write("display value of a variable”+msg)
</script>
</body>

Data Types in JavaScript


• JavaScript is a free-form language. Need not declare all variables, classes,
and methods
• Variables in JavaScript can be of type:
 Number (4.156, 39)
 String (“This is JavaScript”)
 Boolean (true or false)
 Null (null)  usually used to indicate the absence of a value

• Defining variables. var variableName = value


• JavaScript variables are said to be un-typed or loosely typed
 letters of the alphabet, digits 0-9 and the underscore (_) character and is case-
sensitive.
 Cannot include spaces or any other punctuation characters.
 First character of name must be either a letter or the underscore character.
 No official limit on the length of a variable name, but must fit within a line.
Javascript operators:

Control Structures and Loops


• JavaScript supports the usual control structures:
 the conditionals: if(condition) { if(a>10) {
o if, statement 1 document.write(“Greater than 10”)
o if...else } else { } else {
statement 2 document.write(“Less than 10”)
o If … else if … else
} }
o Switch
document.write( (a>10) ? “Greater than 10” : “Less than 10” );
switch (variable) {
 iterations: case outcome1 :{
o for //stmts for outcome 1
break; }
o while
case outcome2 :{
//stmts outcome 2
break; }
default: {
//none of the outcomes is chosen
for( [initial expression;][condition;][increment expression] ) { }
statements }
}

for(var i=0;i<10;i++) while(condition) { while(i<10) {


{ statements document.write(“Hello”);
document.write(“Hello”); } i++;
} }
JavaScript Functions
function myFunction (arg1, arg2, arg3) Calling the function :
{ myFunction( “abc”, “xyz”, 4 )
statements myFunction()
return
}

function area(w1, w2, h) { function diameter(radius){


var area=(w1+w2)*h/2; return radius * 2;
alert(area+" sq ft"); }
}
area(2,3,7); //calling the function var d=diameter(5); //calling the function

• Function expressions - functions are assigned to variables

var area = function (radius) {


return Math.PI * radius * radius;
};
alert(area(5)); // => 78.5

Global and Local Variables


<script language=“Javascript”>
var companyName=“TechnoFlo”
function f(){
var employeeName=“Henry”
document.write(“Welcome to ”+companyName+ ”, “ +employeeName)
}
</script>

• Variables that exist only inside a function are called Local variables
• Variables that exist throughout the script are called Global variables
 Their values can be changed anytime in the code and even by other functions
Predefined Functions
• isFinite: evaluates an argument to determine if it is a finite number.

isFinite (number) //where number is the number to evaluate

• isNaN : Evaluates an argument to determine if it is “NaN” (not a number)


o isNaN (testValue), where testValue is the value you want to evaluate

isNaN(0) //false
• Parseint and parsefloat isNaN('123') //false
isNaN('Hello') //true
 Returns a numeric value for string argument.
 parseInt (str)
 parseFloat (str)
parseInt() interprets any
parseInt("3 blind mice") // => 3 number beginning with “0x” or
parseFloat(" 3.14 meters") // => 3.14 “0X” as hexadecimal no
parseInt("-12.34") // => -12
parseInt("0xFF") // => 255
parseInt("0xff") // => 255
parseInt("-0XFF") // => -255
parseFloat(".1") // => 0.1
parseInt("0.1") // => 0
2.4: JavaScript Functions
parseInt(".1") // => NaN: integers can't start with "."
parseFloat("$72.47"); // => NaN: numbers can't start with "$"

Predefined Core Objects


Lesson 10. Cascading Style Sheets
65

String Objects
• Creating a string object:
 var myString = new String(“characters”)
 var myString = “fred”

• Properties of a string object:


 length: returns the number of characters in a string.
• “Lincoln”.length // result = 7
• “Four score”.length // result = 10
• “One\ntwo”.length // result = 7
• “”.length // result = 0
• String Object methods:
 charAt(index) : returns the character at a specified position.
o Eg : var str = "Hello world!";
• str.charAt(0); //returns H
• str.charAt(str.length-1)); //returns !
 concat() : joins two or more strings
o stringObject.concat(stringX,stringX,...,stringX)
o Eg: var str1="Hello ";
var str2="world!";
document.write(str1.concat(str2));

66

String functions
• indexOf () : returns the position of the first occurrence of a specified string
value in a string.
 index values start their count with 0.
 If no match occurs within the main string, the returned value is -1.
 string.indexOf( searchString [, startIndex])

Eg : var str="Hello world, welcome";


str.indexOf("Hello"); //returns 0
str.indexOf("wor")); //returns 6
str.indexOf("e",5); //returns 14

• toLowerCase() / toUpperCase()
Eg: var str="Hello World!";
str.toLowerCase() //returns hello world
str.toUpperCase() //returns HELLO WORLD
• slice( startIndex [, endIndex])
 Extracts a part of a string and returns the extracted part in a new string

Eg : var str=“Hello World";


str.slice(6) //returns World
str.slice(0,1) //returns H
67

String functions
• split(“delimiterCharacter”[, limitInteger]) - Splits a string into array of strings
 string.split(“delimiterCharacter”[, limitInteger])
Output :
var str = "zero one two three four"; zero
var arr = str.split(" ");
one
for(i = 0; i < str.length; i++){ document.write(“<br>” + arr[i]); }
two
var myString = “Anderson,Smith,Johnson,Washington” three
var myArray = myString.split(“,”) four
var itemCount = myArray.length // result: 4

 Complete Example: var s = "hello, world" // Start with some text.


s.charAt(0) // => "h": the first character.
s.charAt(s.length-1) // => "d": the last character.
s.substring(1,4) // => "ell": the 2nd, 3rd and 4th characters.
s.slice(1,4) // => "ell": same thing
s.slice(-3) // => "rld": last 3 characters
s.indexOf("l") // => 2: position of first letter l.
s.lastIndexOf("l") // => 10: position of last letter l.
s.indexOf("l", 3) // => 3: position of first "l" at or after 3
s.split(", ") // => ["hello", "world"] split into substrings
s.replace("h", "H") // => "Hello, world": replaces all instances
s.toUpperCase() // => "HELLO, WORLD"

68

Date
• Date object allows the handling of date and time information.
 All dates are in milliseconds from January 1, 1970, 00:00:00.
 Dates before 1970 are invalid dates.
• There are different ways to define a new instance of the date object:
var d = new Date() //Current date
var d = new Date(milliseconds)
var d = new Date(dateString)
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds)

<script>
var d=new Date();
document.write(d);
</script>

var d = new Date(86400000);


var d = new Date(99,5,24,11,33,30,0);
Date Object - Methods
• getDate( ) Date of the month (1 - 31)
• getDay( ) Day of the week (0 - 6, 0-Sunday)
• getMonth( ) The month (0 - 11, 0 - Jan.)
• getFullYear( ) The year (4 digits)
• getHours( ) Hour of the day (0 - 23)
• getMinutes( ) Minutes (0 - 59)
• getSeconds( ) Seconds (0 - 59)
• getTime( ) Milliseconds since 1/1/1970
• getTimezoneOffset( ) Offset between local time and GMT
• setDate(dayValue) 1-31
• setHours(hoursValue) 0-23
• setMinutes(minutesValue) 0-59
• setMonth(monthValue) 0-11
• setSeconds(secondsValue) 0-59
• setTime(timeValue) >=0
• setYear(yearValue) >=1970

70

Array
• An array is data structure for storing and manipulating ordered collections of
data.
• An array can be created in several ways.
 Eg1: Regular: ----------------------------------------- var cars=new Array();
 Eg 2: Condensed: cars[0]="Spark";
o var cars=new Array("Spark","Volvo","BMW");
cars[1]="Volvo";
cars[2]="BMW";
 Eg 3: Literal:
o var cars=["Spark","Volvo","BMW"];
 Eg 4: var matrix = [[1,2,3], [4,5,6], [7,8,9]];
 Eg 5 : var sparseArray = [1,,,,5];

• Deleting an array element eliminates the index from the list of accessible index
values
 delete is a unary operator that attempts to delete myArray.length// result: 5
the object property or array element specified delete myArray[2]
myArray.length// result: 5
 This does not reduce array’s length
myArray[2] // result: undefined
71

Array Object Methods


 arrayObject.reverse()
 arrayObject.slice(startIndex, [endIndex])
 arrayObject.join(separatorString) : array contents will be joined and placed into
arrayText by using the comma separator“
 arrayObject.push(): add one or more values to the end of an array

arrayObject.slice(startIndex [, endIndex]) //Returns: Array


var solarSys = new Array (“Mercury”,”Venus”,”Earth”,”Mars”,”Jupiter”,”Saturn”)
var nearby = solarSys.slice(1,4)
// result: new array of “Venus”, “Earth”, “Mars”

arrayObject.concat(array2)
var arrayText = myArray.join(“,”)
var a1 = new Array(1,2,3)
var a2 = new Array(“a”,”b”,”c”)
var a3 = a1.concat(a2)
// result: array with values 1,2,3,”a”,”b”,”c”

a = []; // Start with an empty array


a.push("zero") // Add a value at the end. a = ["zero"]
a.push("one", "two") // Add two more values. a = ["zero", "one", "two"]

Creating New Objects


1. Using Object Initializers
 Syntax : objName = {property1:value1, property2:value2, … }
 person = { "name ":"amit", "age":23};
 myHonda = {color:“red”, wheels:4, engine:{cylinders:4, size:2}}
2. Using Constructors
 Define the object type by writing a constructor function.
 Create an instance of the object with new.

function car(make, model, year) { function person(name, age) {


this.make = make this.name = name
this.model = model this.age = age
this.year = year }
} ken = new person( “Ken” , 33 )
…..
mycar = new car( “Ford” , “Mustang” , 2013)
function car(make, year, owner) {
this.make = make
this.year = year
this.owner = owner
}
car1 = new car( “Mazda”, 1990, ken )
Creating New Objects (Contd.)
• Accessing properties car2.owner.name car1.make = “corvette”
• Defining methods

 Example:
obj.methodName = function_name
obj.methodName(params)

function car(make, model, year, owner) {


this.make = make;
this.model = model;
this.year = year;
this.displayCar = displayCar;
}
function displayCar() {
document.writeln( “A beautiful” + this.year
+ “ ” + this.make + “ ” + this.model
}
….
car1.displayCar(); car2.displayCar()

Examples : Using Object Initializers


75

JavaScript Document Object Model

76

Window Object Methods


• alert(message)
 window.alert(“Display Message”)
• confirm(message)
 window.confirm(“Exit Application ?”)
• prompt(message,[defaultReply])
 var input=window.prompt(“Enter value of X”)

• window.open(URL,name,specs)
 URL : Specifies the URL of the page to open. If no URL is specified, a new window
with about:blank is opened
 Name : Specifies the target attribute or the name of the window.
 Specs : comma-separated list of items.

myWindow=window.open('','','width=200,height=100');
myWindow.document.write("<p>This is 'myWindow'</p>"); example opens an
myWindow.focus(); about:blank page in a new
browser window:
77

setInterval and setTimeout methods

Document Object
 When an HTML document is loaded into a web browser, it becomes a document
object; root node of the HTML document and owns all other nodes
Examples : Modifying content

Example : Modifying styles


Mouse events

Form validation
Example

Example
Example

<SCRIPT>
function valSelected(){
var radio = document.getElementsByClassName("r1");
for(var i = 0; i < radio.length; i++){
if(radio[i].checked) console.log("coffee selected : " + radio[i].value);
}
var checklist = document.getElementsByClassName("c1");
for(i=0;i<checklist.length;i++){
if (checklist[i].checked == true) console.log("Music selected : " + checklist[i].value);
}
</SCRIPT>
<FORM NAME="selectForm">
<B>Which Music types do you like?</B>
<input type="checkbox" class="c1" id="c1" value="blues">Blues</input>
<input type="checkbox" class="c1" id="c2" value="classical">Classical</input>
<input type="checkbox" class="c1" id="c3" value="opera">Opera</input>
<b>Choose Coffee to go with your music!</b><br>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="cappuchino">Cappuchino </input>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="latte">Latte</input>
<INPUT TYPE="radio" name="coffee" class="r1" id="coffee" VALUE="Mocha">Mocha</input>
<INPUT TYPE="button" VALUE="Which option selected?" onClick="valSelected()">
</FORM>

Regular Expressions
• A regular expression is an object that describes a pattern of characters.
 Its matched against a text string, when you perform searches & replacements
 Perform client-side data validations or any other extensive text entry parsing
 RegExp objects may be created either with the RegExp() constructor or using a special
literal syntax.
 regular expression literals are specified as characters within a pair of slash (/)

var re = / / simple pattern to match the space character

var re = / /g matching a string on a global basis


var re = /web/i a case-insensitive match

var
 Eg
re = /web/gi expression is both case-insensitive and global

i Perform case-insensitive matching


str = "I love JavaScript!"; g Perform a global match (find all matches
regexp = /love/; rather than stopping after the first match)
alert( str.search(regexp) ); // 2
m Perform multiline matching
RegEx – Special Characters
• \b Word Boundary:
 Get a match at the beginning or end of a word in the string
o /\bor/ matches “origami” and “or” but not “normal”.
o /or\b/ matches “traitor” and “or” but not “perform”
o /\bor\b/ matches full word “or” and nothing else

• \B Word Non-Boundary:
 Get a match when it is not at the beginning or end of a word in the string
o /\Bor/ matches “normal” but not “origami”
o /or\B/ matches “normal” and “origami” but not “traitor”
o /\Bor\B/ matches “normal” but not “origami” or “traitor”

RegEx – Special Characters (Contd.)


• \d Numeral: Find any single digit 0 through 9
o /\d\d\d/ matches “212” and “415” but not “B17”

• \D Non-numeral: Find any non-digit


o /\D\D\D/ matches “ABC” but not “212” or “B17”

• \s Single White Space: Find any single space character


o /over\sbite/ matches “over bite” but not “overbite” or “over bite”

• \S Single Non-White Space:


o /over\Sbite/ matches “over-bite” but not “overbite” or “over bite”

• \w Letter, Numeral, or Underscore:


o /A\w/ matches “A1” and “AA” but not “A+”

• \W Not letter, Numeral, or Underscore:


o /A\W/ matches “A+” but not “A1” and “AA”
RegEx – Special Characters (Contd.)
• “.” Any Character Except Newline:
o /…/ matches “ABC”, “1+3”, “A 3” or any 3 characters

• […] Character Set: any character in the specified character set


o /[AN]BC/ matches “ABC” and “NBC”

• [^…] Negated Character Set: any character not in the specified character set
o /[^AN]BC/ matches “BBC” and “CBC” but not “ABC” or “NBC”

• Positional Metacharacters
• “^” - At the beginning of a string or line
o /^Fred/ matches “Fred is OK” but not “I’m with Fred” or “Is Fred here?”
• “$” - At the end of a string or line
o /Fred$/ matches “I’m with Fred” but not “Fred is OK” or “Is Fred here?”

RegEx – Counting Metacharacters

• “*” - Zero or More Times:


o /Ja*vaScript/ matches “JvaScript”, “JavaScript” & “JaaavaScript” but not “JovaScript”

• “?” - Zero or One Time:


o /Ja?vaScript/ matches “JvaScript” or “JavaScript” but not “JaaavaScript”

• “+” - One or More Times:


o /Ja+vaScript/ matches “JavaScript” or “JaavaScript” but not “JvaScript”

• {n} - Exactly n Times:


o /Ja{2}vaScript/ matches “JaavaScript” but not “JvaScript” or “JavaScript”

• {n,} - N or More Times:


o /Ja{2,}vaScript/ matches “JaavaScript” or “JaaavaScript” but not “JavaScript”

• {n,m} - At Least n, At Most m Times:


o /Ja{2,3}vaScript/ matches “JaavaScript” or “JaaavaScript” but not “JavaScript”
Regular Expression Object
• Create Regular Expression:
regExpObject = /pattern/ [g | i | gi]
regExpObject = new RegExp(pattern, flag)

 Eg: re = new RegExp( "pushing", "g" );


 Eg: var zipcode = new RegExp("\\d{6}", "g");

• Methods that use regular expressions

Method Description
executes a search for a match in a string. It returns an array of information or null
exec() on a mismatch.
test() tests for a match in a string. It returns true or false
executes a search for a match in a string. It returns an array of information or null
match() on a mismatch.
search() tests for a match in a string; returns the index of the match, or -1 if search fails
executes a search for a match in a string, and replaces the matched substring with
replace() a replacement substring.
split() uses a reg exp or a fixed string to break a string into an array of substrings.

var pattern = /java/g;


var text = "JavaScript is more fun than java!";
var result = pattern.exec(text)
console.log(result) //["java", index: 28, input: "JavaScript is more fun than java!"]

When there’s a "g" flag, then str.match returns an array of all matches. There are no
additional properties in that array, and parentheses do not create any elements.
With no “g” flag, looks for the first match only.

let str = "HO-Ho-ho!";


let result = str.match( /ho/ig ); //global search
alert( result ); // HO, Ho, ho (all matches, case-insensitive)

s1 = "how are you all doing";


var re = new RegExp("o","g");
console.log(s1.replace(re,"z")); //hzw are yzu all dzing
Demo
AJAX & JSON

JSON (JavaScript Object Notation)


• JSON is a simple and easy to read and write data exchange format.
 It is easy for humans to read and write and easy for machines to parse and generate.
 It is based on a subset of the JavaScript, Standard ECMA-262
 JSON is a text format that is completely language independent; can be used with most of the
modern programming languages.
 The filename extension is .json
 JSON Internet Media type is application/json
 It’s popular and implemented in countless projects worldwide, for those don’t like XML, JSON is a
very good alternative solution.

• Values supported by JSON


 Strings : double-quoted Unicode, with backslash escaping
 Numbers:
o double-precision floating-point format in JavaScript
 Booleans : true or false
 Objects: an unordered, comma-separated collection of key:value pairs enclosed in curly braces,
with the ':' character separating the key and the value; the keys must be strings and should be
distinct from each other
 Arrays : an ordered, comma-separated sequence of values enclosed in square brackets; the
values do not need to be of the same type
 Null : A value that isn't anything
Demo

Demo
What is Ajax ?
• “Asynchronous JavaScript And XML”
 AJAX is not a programming language, but a technique for making the user
interfaces of web applications more responsive and interactive
 It provide a simple and standard means for a web page to communicate with the
server without a complete page refresh.

Why Ajax?
• Intuitive and natural user interaction
• No clicking required. Call can be triggered on any event
• Mouse movement is a sufficient event trigger
• "Partial screen update" replaces the "click, wait, and refresh" user interaction
model
• Only user interface elements that contain new information are updated (fast
response)
• The rest of the user interface remains displayed as it is without interruption
(no loss of operational context)

XMLHttpRequest
• JavaScript object - XMLHttpRequest object for asynchronously exchanging the
XML data between the client and the server

• XMLHttpRequest Methods
 open(“method”, “URL”, syn/asyn) : Assigns destination URL, method, mode
 send(content) : Sends request including string or DOM object data
 abort() : Terminates current request
 getAllResponseHeaders() : Returns headers (labels + values) as a string
 getResponseHeader(“header”) : Returns value of a given header
 setRequestHeader(“label”,”value”) : Sets Request Headers before sending

• XMLHttpRequest Properties
 Onreadystatechange : Event handler that fires at each state change
 readyState values – current status of request
 Status : HTTP Status returned from server: 200 = OK
 responseText : get the response data as a string
 responseXML : get the response data as XML data
Creating an AJAX application
• Step 1: Get an instance of XHR object

if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...


xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

• Step 2: Make the request


xhr.open('GET', 'http://www.example.org/some.file', true);
xhr.send(null);

xhr.open("POST", "AddNos.jsp");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("tno1=100&tno2=200");

• Step 3 : Attach callback function to xhr object

httpRequest.onreadystatechange = function(){
// process the server response
};

Ajax Demo
AJAX Demo with XML

AJAX Demo with JSON


JQUERY

Software

• Choosing a Text Editor


 Text editors that support jQuery include Brackets, Sublime Text, Kwrite, Gedit,
Notepad++, PSPad, or TextMate.
jQuery Introduction

• jQuery is a lightweight, cross browser and feature-rich JavaScript library which


is used to manipulate DOM
 Originally created by John Resig in early 2006.
 The jQuery project is currently run and maintained by a distributed group of
developers as an open-source project.

• Why jQuery
 JavaScript is great for a lot of things especially manipulating the DOM but it’s pretty
complex stuff. DOM manipulation is by no means straightforward at the base level,
and that’s where jQuery comes in. It abstracts away a lot of the complexity involved in
dealing with the DOM, and makes creating effects super easy.
 It can locate elements with a specific class
 It can apply styles to multiple elements
 It solves the cross browser issues
 It supports method chaining
 It makes the client side development very easy

Including jQuery in HTML Document

• jQuery library can be included in a document by linking to a local copy or to one


of the versions available from public servers.
• Eg : include a local copy of the jQuery library

• Eg : include the library from a publicly available repository


 There are several well-known public repositories for jQuery; these repositories are also
known as Content Delivery Networks (CDNs).
Using jQuery

<html>
<head>
<title>Test jQuery</title>
<script type="text/javascript" src="jquery-3.5.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('Hi');
});
</script>
</head>
<body>
Welcome to jQuery
</body>
</html>

$(function() {
// jQuery code
});

Introduction to selectors

• jQuery uses same CSS selectors used to style html page to manipulate elements
 CSS selectors select elements to add style to those elements where as jQuery selectors
select elements to add behavior to those elements.
 Selectors allow page elements (Single or Multiple) to be selected.
• Selector Syntax
 $(selectorExpression)
 jQuery(selectorExpression)
 $(selector).action()
Selectors
• Selecting by Tag Name:
• Selecting single tag takes the following syntax
 $(‘p’) – selects all <p> elements
 $(‘a’) – selects all <a> elements
• To reference multiple tags, use the ( , ) to separate the elements
 $(‘p, a, span’) - selects all paragraphs, anchors and span elements

• Selecting Descendants
• $(‘ancestor descendant’) - selects all the descendants of the ansector
 $(‘table tr’) - Selects all tr elements that are the descendants of the table element
• Descendants can be children, grand children etc of the designated ancestor
element.

Demo
Selecting by Element ID
• It is used to locate the DOM element very fast.
• Use the # character to select elements by ID
 $("#first") — selects the element with id="first"
 $(‘#myID’) – selects the element with id=" myID "

Selecting Elements by Class Name


• Use the ( . ) character to select elements by class name
 $(".intro") — selects all elements with class="intro"
• To reference multiple tags, use the ( , ) character to separate class name.
 $(‘.blueDiv, .redDiv’) - selects all elements containing class blueDiv and redDiv
• Tag names can be combined with elements name as well.
 $(‘div.myclass’) – selects only those <div> tags with class=“myclass”
Selecting by attribute values
• Use brackets [attribute] to select on attribute name and/or attribute value
 $(‘a[title]’) - selects all anchor elements that have a title attribute
 $(‘a[title=“trainer”]’) – selects all <a> elements that have a “trainer” title attribute value

Selecting by input elements


• To select input elements of type : <input>:
 $('input[type="text"]').css("background", "yellow");

• To select all input elements


 $(‘:input’) - Selects all form elements (input, select, textarea, button).
 $(‘:input[type=“radio”]’) – selects all radio buttons

 $(":text") - All input elements with type="text"


 $(":password") - All input elements with type="password"
 $(":radio") - All input elements with type="radio"
 $(":checkbox") - All input elements with type="checkbox"
 $(":submit") - All input elements with type="submit"
 $(":reset") - All input elements with type="reset"
 $(":button") - All input elements with type="button"
 $(":file") - All input elements with type="file"
Basic Filters

• The index-related selectors (:eq(), :lt(), :gt(), :even, :odd) filter the set of elements
that have matched the expressions that precede them.
 They narrow the set down based on the order of the elements within this matched set.
 Eg, if elements are first selected with a class selector (.myclass) and four elements are
returned, these elements are given indices 0 through 3
• eq() - Select the element at index n within the matched set.
 Eg : $("p:eq(1)") - Select the second <p> element
 Eg : $("element:eq(0)") is same as $(‘element:first-child’)

• $(‘element:odd’) and $(‘element:even’) selects odd and even positions


respectively. 0 based indexing
 Odd returns (1,3,5…) and Even returns (0,2,4…)

• :gt() and lt() - Select all elements at an index > or < index within the matched set
 Eg : $("tr:gt(3)") : Select all <tr> elements after the 4 first
 Eg : $("tr:lt(4)") : Select the 4 first <tr> elements
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
<script>
$( "td:eq( 2 )" ).css( "color", "red" );
//$( "tr:first" ).css( "font-style", "italic" ); //is same as below line
$( "tr:eq(0)" ).css( "font-style", "italic" );
$( "td:gt(4)" ).css( "backgroundColor", "yellow" );
</script>

<script type="text/javascript">
$(document).ready(function() {
$('tr:odd').css('background-color','tomato');
$('tr:even').css('background-color','bisque');
});
</script>
<table border=1 cellspacing=5 cellpadding=5>
<th>column 1<th>column 2<th>column 3
<tr><td>data 1</td><td>data 2</td><td>data 3
<tr><td>data 4<td>data 5<td>data 6
<tr><td>data 7<td>data 8<td>data 9
<tr><td>data 10<td>data 11<td>data 12
</table>

Basic Filters continued


• :first , :last - Selects the first/last matched element.
 :first is equivalent to :eq( 0 ) and :lt(1). This matches only a single element, whereas, :first-
child can match more than one; one for each parent.
• :header - Selects all elements that are headers, like h1, h2, etc
Basic Filters continued
• :not - Selects all elements that do not match the given selector.
 Eg : $("p:not(.intro)") - Select all <p> elements except those with class="intro"
 Eg : $('a:not(div.important a, a.nav)'); - // Selects anchors that do not reside within
'div.important' or have the class 'nav’

Child Filter
• $(‘element:first-child’) and $(‘element:last-child’) selects the first child & last child
of its parent.
 $(‘span:first-child’) returns the span which is a first child for all the groups
• :nth-child() - Selects all elements that are the nth-child of their parent. 1-based
indexing
 Eg : $("p:nth-child(3)") - Select each <p> element that is the third child of its parent
Content Filters
• :contains() will select elements that match the contents.
 $(‘div:contains(“hello”)’) - selects div’s which contains the text hello (match is case
sensitive)

• :empty - Select all elements that have no children (incl text nodes)

• :has : Selects elements which contain at least one element that matches the
specified selector.
 Eg : $("p:has(span)") - Select all <p> elements that have a <span> element inside of
them
 Eg : $("div:has(p,span,li)").css("border","solid red"); - Select all <div> elements that have
at least one of the given elements inside

• :parent - Select all elements that have at least one child node (either an element
or text).
 Eg : $("td:parent") - Select all <td> elements with children, including text
jQuery Traversing -> filtering

• .eq() - Reduce the set of matched elements to the one at the specified index.
 Eg : $("p").eq(1).css("background-color","yellow") - Select the second <p> element (index
number 1)

• .filter() - Reduce the set of matched elements to those that match the selector or
pass the function's test
 Eg : $("p").filter(".intro") - Return all <p> elements with class "intro“

• .first() / last()
 Eg : $("div p").first() - Select first <p> element inside first <div> element

• .has() - Reduce the set of matched elements to those that have a descendant that
matches the selector or DOM element.
 Eg : $("p").has("span") - Return all <p> elements that have <span> element inside
jQuery Traversing -> Tree Traversal

• .children() - Returns all direct children of the selected element


 Eg : $("ul").children().css({"color":"red","border":"2px solid red"}) - Return elements that
are direct children of <ul>

• .find() - Returns descendant elements of the selected element


 Eg : $("ul").find("span").css({"color":"red","border":"2px solid red"}) - Return all <span>
elements that are descendants of <ul>
• .next() / prev() - Returns the next / previous sibling element of the selected
element
• nextAll() - returns all next sibling elements of the selected element
• parent() - Returns the direct parent element of the selected element
Method Chaining
• Chaining is a good way to avoid selecting elements more than once. Eg:
 $("div").fadeOut();
 $("div").css("color", "red");
 $("div").text("hello world");

• Instead of doing that and running $(“div”) three times, you could do this:
$("div").fadeOut().css("color", "red").text("hello world");

Iterating through Nodes


• .each(function(index,Element)) is used to iterate through jQuery objects.
 jQuery 3 also allows to iterate over the DOM elements of a jQuery collection using the
for...of loop.
Working with Attributes
• Object attributes can be used using attr():
 var val = $(‘#customDiv’).attr(‘title’); - Retrieves the title attribute value

• .attr(attributeName,value) : accesses an object’s attributes and modifies the


values.
 $(‘img’).attr(‘title’,’Image title’); - changes the title attribute value to Image title.

• To modify multiple attributes, pass JSON object.

• You can also remove attributes entirely using .removeAttr().


attributes-demo.html

Getting Content

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


• html() - Sets or returns the content of selected elements (including HTML markup)
• val() - Sets or returns the value of form fields

$.html() treats the string as HTML, $.text() treats the content as text
Getting Content

var input = $( 'input[type="text"]' );


input.val( 'new value' );
input.val(); // returns 'new value'

Adding and Removing Nodes


• In traditional approach adding and removing nodes is tedious.
• To insert nodes four methods available:
• Appending adds children at the end of the matching elements
 .append()
 .appendTo()
• Prepending adds children at the beginning of the matching elements
 .prepend()
 .prependTo()
• To wrap the elements use .wrap()
 Eg: $(“p”).wrap(“<h1></h1>”) //wraps “p” in <h1> tags
• To remove nodes from an element use .remove()
Modifying Styles
• .css() function is used to modify an object’s style
 $('div').css('color','red'); $('div').css({
“color”:”red”,
• Multiple styles can be modified by passing a JSON Object
“font-weight”:”bold”
});
Working with Classes
• The four methods for working with css class attributes are
• .addClass() : adds one or more classes to the class attribute of each element.
 $(‘p’).addClass(‘classOne’);
 $(‘p’).addClass(‘classOne classTwo’);
• .hasClass() : returns true if the selected element has a matching class
 if($('p').hasClass('classOne')) { //perform operation}
• removeClass() remove one or more classes
 $(‘p’).removeClass(‘classOne classTwo’);
• To remove all class attributes for the matching selector
 $(‘p’).removeClass();
• .toggleClass() : alternates adding or removing a class based on the current
presence or absence of the class.
 $(‘#targetDiv’).toggleClass('highlight');
Working with Classes (Contd)

jQuery Event Model Benefits

• Events notify a program that a user performed some type of action


• jQuery Events
 click() $("img").mouseover(function () {
 blur() $(this).css("opacity", "0.3");
});
 focus()
$("img").mouseout(function () {
 dblclick() $(this).css("opacity", "1.0");
 mousedown() });

 mouseup()
 mouseover()
 keydown()
 keypress()
 hover() : hover() method takes two functions
and is a combination of the mouseenter() $("#p1").hover(function(){
and mouseleave() methods. alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});
Handling Click Events
• .click(handler([eventObject])) is used to listen for a click event or trigger a click
event on an element
 $(‘#submitButton’).click(function() { alert(‘Clicked’) });
Using on() and off()
• The on() method attaches one or more event handlers for the selected elements.

$( "#dataTable tbody tr" ).on( "click", function() {


console.log( $( this ).text() );
});
Showing and Hiding Elements
• To set a duration and a callback function
 show(duration, callback)
 duration is the amount of time taken (in milliseconds), and callback is a callback function
jQuery will call when the transition is complete.
• The corresponding version of hide( )
 hide(duration, callback)
• To toggle an element from visible to invisible or the other way around with a
specific speed and a callback function, use this form of toggle( )
 toggle(duration, callback)
jQuery Sliding Effects
• The jQuery slide methods slide elements up and down.
• jQuery has the following slide methods:
 $(selector).slideDown(speed,callback) : Display the matched elements with a sliding
motion
 $(selector).slideUp(speed,callback) : Hide the matched elements with a sliding
motion.
 $(selector).slideToggle(speed,callback)
• The speed parameter can take the following values: "slow", "fast", "normal",
or milliseconds.
• The callback parameter is the name of a function to be executed after the
function completes.

$("#flip").click(function(){
$("#panel").slideDown();
});

jQuery Fading Effects


• The jQuery fade methods gradually change the opacity for selected elements.
• jQuery has the following fade methods:
 $(selector).fadeIn(speed,callback)
 $(selector).fadeOut(speed,callback)
 $(selector).fadeTo(speed,opacity,callback)
• The speed parameter can take the following values: "slow", "fast", "normal", or
milliseconds.
 The opacity parameter in the fadeTo() method allows fading to a given opacity.
 The callback parameter is the name of a function to be executed after the function
completes.

$('.blueDiv').fadeTo(1000,0.1,function(){
$('#results').text('FadeTo Animation Completed');
});
Creating Custom Animation
• Custom animation can be created in jQuery with the animate() function
 animate(params, duration, callback)
o params contains the properties of the object you’re animating, such as CSS properties, duration is
the optional time in milliseconds that the animation should take and callback is an optional
callback function.

<style type="text/css">
#content { background-color:#ffaa00; width:300px; height:30px; padding:3px; }
</style>
<script type="text/javascript">
$(document).ready(function() {
$("#animate").click(function() {
$("#content").animate({"height": "100px", "width": "350px"}, "slow");
});
});
</script>
</head>
<body>
<input type="button" id="animate" value="Animate"/>
<div id="content">Animate Height</div> </body>

jQuery Ajax features

• The jQuery library has a full suite of Ajax capabilities.


 The functions and methods therein allow us to load data from the server without a
browser page refresh.
 $(selector).load() : Loads HTML data from the server
 $.get() and $.post() : Get raw data from the server
 $.getJSON() : Get / Post and return JSON data
 $.ajax() : Provides core functionalityjQuery Ajax functions works with REST APIs,
Webservices and more
Loading HTML content from server

• $(selector).load(url,data,callback) allows HTML content to be loaded from a


server and added into DOM object.
 $("#targetDiv").load('GetContents.html');
• A selector can be added after the URL to filter the content that is returned
from the calling load().
 $("#targetDiv").load('GetContents.html #Main');
• Data can be passed to the server using load(url,data)
 $('#targetDiv').load('Add.aspx',{firstNumber:5,secondNumber:10})
• load () can be passed a callback function

$(‘#targetDiv’).load(‘Notfound.html’, function (res,status,xhr) {


if (status == “errror”) {
alert(xhr.statusText);
}
});

Using get(), getJSON() & post()


• $.get(url,data,callback,datatype) can retrieve data from a server.
 datatype can be html, xml, json

$.get('GetContents.html',function(data){
$('#targetDiv').html(data);
},'html');

• $.getJSON(url,data,callback) can retrieve data from a server.

$.getJSON('GetContents.aspx,{id:5},function(data){
$('#targetDiv').html(data);
});

• $.post(url,data,callback,datatype) can post data to a server and retrieve


results.
Using ajax() function

• ajax() function is configured by assigning values to JSON properties

$.ajax({
url: “employee.asmx/GetEmployees",
data : null,
contentType: "application/json; charset=utf-8",
datatype: ‘json’,
success: function(data,status,xhr){
//Perform success operation
},
error: function(xhr,status,error) {
//show error details
}
});

NODE.JS
Server Side Javascript
Node.js – an intro
• In 2009 Ryan Dahl created Node.js or Node, a framework primarily used to create highly
scalable servers for web applications.
 Node.js is an open source, cross-platform runtime environment for server-side JavaScript.
 Node.js is required to run JavaScript without a browser support. It uses Google V8 JavaScript engine to
execute code.
 It is written in C++ and JavaScript.
 Node.js is a development framework that is based on Google’s V8 JavaScript engine that powers
Google's Chrome web browser.
 You write Node.js code in JavaScript, and then V8 compiles it into machine code to be executed.

 It’s a highly scalable system that uses asynchronous, non-blocking I/O model (input/output), rather than
threads or separate processes
 It is not a framework like jQuery nor a programming language like C# or JAVA; Its primarily a Javascript
engine

Node.js is really two things: a runtime environment and a library

Traditional Programming vs Event-driven programming


• In traditional programming I/O is performed in the same way as it does local function calls.
i.e. Processing cannot continue until the operation is completed.
 When the operation like executing a query against database is being executed, the whole
process/thread idles, waiting for the response. This is termed as “Blocking”
 Due to this blocking behavior we cannot perform another I/O operation, the call stack becomes
frozen waiting for the response.

• Event-driven programming or Asynchronous programming is a programming style where


the flow of execution is determined by events.
• Events are handled by event handlers or event callbacks
 An event callback is a function that is invoked when something significant happens like when the user
clicks on a button or when the result of a database query is available.

• This style of programming — whereby instead of using a return value you define functions
that are called by the system when interesting events occur — is called event-driven or
asynchronous programming.
Typical blocking I/O
programming
result = query('SELECT * FROM posts WHERE id = 1');
do_something_with(result);
query_finished = function(result) {
do_something_with(result);
}
query('SELECT * FROM posts WHERE id = 1', query_finished);
Event loop
• An event loop is a construct that mainly performs two functions in a continuous loop —
event detection and event handler triggering.
 In any run of the loop, it has to detect which events just happened.
 Then, when an event happens, the event loop must determine the event callback and invoke it.
• This event loop is just one thread running inside one process, which means that, when
an event happens, the event handler can run without interruption. This means the
following:
 There is at most one event handler running at any given time.
 Any event handler will run to completion without being interrupted.

 Node.js uses the “Single Threaded Event Loop” architecture to handle multiple concurrent clients.

Asynchronous and Event Driven


• All APIs of Node.js library are asynchronous that is, non-blocking.
 It essentially means 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 Node.js helps
the server to get a response from the previous API call.
 It is non-blocking, so it doesn't make the program wait, but instead it registers a callback and lets
the program continue.

• Node.js is not fit for an application which performs CPU-intensive operations like image
processing or other heavy computation work because it takes time to process a request
and thereby blocks the single thread.
• Node.js is great for data-intensive applications.
 Using a single thread means that Node.js has an extremely low-memory footprint when used as
a web server and can potentially serve a lot more requests.
 Eg, a data intensive application that serves a dataset from a database to clients via HTTP

• What Node is NOT!


Node is not a webserver. By itself it doesn't do anything. It doesn't work like Apache. There is no
config file where you point it to you HTML files. If you want it to be a HTTP server, you have to write an
HTTP server (with the help of its built-in libraries). Node.js is just another way to execute code on your
computer.
It is simply a JavaScript runtime.
Setting up Node
• To install and setup an environment for Node.js :
 Download the latest version of Node.js installable archive file from https://nodejs.org/en/
 Double click to run the msi file
 Verify if the installation was successful : node –v in command window.

Using the Node CLI : REPL (Read-Eval-Print-Loop)


• There are two primary ways to use Node.js on your machines: by using the Node Shell or
by saving JavaScript to files and running those.
 Node shell is also called the Node REPL; a great way to quickly test things in Node.
 When you run “node” without any command line arguments, it puts you in REPL

• You can also create a js file and type in some javascript.

//helloworld.js
console.log("Hello World!");
Using the REPL
• To view the options available to you in REPL type .help and press Enter.

Node js Modules
• A module in Node.js is a logical encapsulation of code in a single unit.
 Since each module is an independent entity with its own encapsulated functionality, it can be managed
as a separate unit of work.

• Consider modules to be the same as JavaScript libraries.


 A set of functions you want to include in your application.
 Module in Node.js is a simple or complex functionality organized in JavaScript files which can be
reused throughout a Node.js application.
 A module is a discrete program, contained in a single file in Node.js. Modules are therefore tied to files,
with one module per file.

• Node.js has a set of built-in modules which you can use without any further installation.
 Built-in modules provide a core set of features we can build upon.
 Also, each module can be placed in a separate .js file under a separate folder.
 To include a module, use the require() function with the name of the module.

• In Node, modules are referenced either by file path or by name


 For example, we can require some native modules:

var http = require('http');


var dns = require('dns'); var myFile = require('./myFile'); // loads myFile.js
Node.js Web App Import required module using require;
load http module and store returned
//RunServer.js HTTP instance into http variable
var http = require("http");
createServer() : turns your computer
function process_request(req, res) { into an HTTP server
var body = ‘Hello World\n'; Creates an HTTP server which listens
var content_length = body.length ; for request over 1337 port on local
machine
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain‘ });

res.end(body);
}

var srv = http.createServer(process_request);


srv.listen(1337, '127.0.0.1’);

console.log('Server running at http://127.0.0.1:1337/');

var http = require('http');


http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
})
.listen(1337, '127.0.0.1');

Node.js Module
• Node.js includes three types of modules:
 Core Modules
 Local Modules
 Third Party Modules

• Loading a core module


 Node has several modules compiled into its binary distribution called core modules.
 It is referred solely by the module name, not by the path and are preferentially loaded even if a third-
party module exists with the same name.
 var http = require('http’);
• Some of the important core modules in Node.js
Node.js Local Module
• The local modules are custom modules that are created locally by developer in the app
 These modules can include various functionalities bundled into distinct files and folders
 You can also package it and distribute it via NPM, so that Node.js community can use it.
 For example, if you need to connect to MongoDB and fetch data then you can create a module for it,
which can be reused in your application.

exports object is a special object created by the Node module system which is returned as the value of
the require function when you include that module.

Create Your Own Modules

• Exports is just module.exports’s little helper. Your module returns module.exports to the caller ultimately,
not exports. All exports does is collect properties and attach them to module.exports
//module7.js //import the assigned properties with a destructuring assignment:
function sayHello(){ const { username, sayHello } = require(‘./module7’)
console.log("Hello World!")
} //Or with a regular assignment and dot notation:

const username = 'Joan' const helloModule = require(‘./module7')

module.exports = {username, sayHello} helloModule.sayHello()


console.log(helloModule.username)
//or, using dot notation:
module.exports.username = username
module.exports.sayHello = sayHello

//alternatively
exports.username = username
exports.sayHello = sayHello

• To Expose properties and functions we use exports


• On other hand, to expose user defined objects (class) and
JSON objects, we use module.exports
Example

NPM (Node Package Manager)


• Loading a module(Third party) installed via NPM
 To use the modules written by other people in the Node community and published on the Internet
(npmjs.com).
 We can install those third party modules using the Node Package Manager which is installed by
default with the node installation.
 Node Package Manager (NPM) is a command line tool that installs, updates or uninstalls
Node.js packages in your application.
 It is also an online repository for open-source Node.js packages. The node community around
the world creates useful modules and publishes them as packages in this repository.
 NPM is a command line tool that installs, updates or uninstalls Node.js packages in your
application.
 After you install Node.js, verify NPM installation : npm -v
NPM (Node Package Manager)
• Installing Packages
 In order to use a module, you must install it on your machine.
 To install a package, type npm install, followed by the package name

• There are two ways to install a package using npm: globally and locally.
• Globally − This method is generally used to install development tools and CLI based
packages. To install a package globally, use the following code.
 npm install -g <package-name>
 Eg to install expressJS : npm install -g express
 Eg to install Typescript : npm install –g typescript
 Eg to install Angular : npm install -g @angular/cli

• Locally − This method is generally used to install frameworks and libraries. A locally
installed package can be used only within the directory it is installed.
 To install a package locally, use the same command as above without the -g flag.
 npm install <package-name>
 Eg : To install cookie parser in Express : npm install --save cookie-parser
 Eg: to install bootstrap : npm install [email protected]

NPM (Node Package Manager)


• When packages are installed, they are saved on local machine
• npm installs module packages to the node_modules folder.

• Installing a package using NPM : $ npm install [g] <Package Unique Name>

• To remove an installed package : npm uninstall [g] < Package Unique Name>

• To update a package to its latest version : npm update [g] < Package Unique Name>
Loading a third party module : package.json
• The package.json file in Node.js is the heart of the entire application.
 It is basically the manifest file that contains the metadata of the project.
 package.json is a configuration file from where the npm can recognize dependencies between packages
and installs modules accordingly.
 It must be located in project’s root directory.
 It contains human-readable metadata about the project (like the project name and description) as well as
functional metadata like the package version number and a list of dependencies required by the
application.
 Your project also must include a package.json before any packages can be installed from NPM.
 Eg : a minimal package.json:

{
"name" : "barebones",
"version" : "0.0.0",
}

o The name field should explain itself: this is the name of your project. The version field is used by npm to make sure
the right version of the package is being installed.

Loading a third party module


• Lets say I want to create a ExpressJS application. I will install ExpressJs locally.
 Step-1) choose a empty folder
 Step-2) run npm init to create a package.json file
 Step-3) install express : npm install express –save (to update package.json)
 Step-4) check the updated json file to see new dependencies

 See how package.json is installed in root folder along with node_modules folder
 My Express app is dependent on a number of other modules
 All these dependencies will have an entry in package.json
Loading a file module
• Loading a file module (User defined module)
 We load non-core modules by providing the absolute path / relative path.
 Node will automatically add the .js extension to the module referred.
 var myModule = require(‘d:/shrilata/nodejs/module'); // Absolute path for module.js
 var myModule = require('../module'); // Relative path for module.js (one folder up level)
 var myModule = require('./module'); // Relative path for module.js (Exists in current directory)

If the given path does not exist, require() will throw an Error with its code property set to
'MODULE_NOT_FOUND'.

package.json
• The package.json file in Node.js is the heart of the entire application.
• It is basically the manifest file that contains the metadata of the project.
• package.json is a configuration file from where the npm can recognize dependencies
between packages and installs modules accordingly.
 It must be located in project’s root directory.

• package-lock.json file
 Introduced in version 5; keeps track of the exact version of every package that is installed so that
a product is 100% reproducible in the same way even if packages are updated by their
maintainers.
 The package-lock.json sets your currently installed version of each package in stone, and npm
will use those exact versions when running npm install.
Buffers
• A buffer is an area of memory; It represents a fixed-size chunk of memory (can't be resized)
allocated outside of the V8 JavaScript engine.
 You can think of a buffer like an array of integers, which each represent a byte of data.
 It is implemented by the Node.js Buffer class.

• Creating Buffer
 It is possible to create your own buffer! Aside from the one Node.js will automatically create during a
stream, it is possible to create and manipulate your own buffer
 A buffer is created using the : Buffer.alloc(), Buffer.allocUnsafe() , Buffer.from()

 Buffer.alloc(size, fill, encoding);


o Size: Desired length of new Buffer. It accepts integer type of data.
o Fill: The value to prefill the buffer. The default value is 0.It accepts any of the following: integer, string, buffer type
of data.
o Encoding: It is Optional. If buffer values are string , default encoding type is utf8. Supported values are:
(“ascii”,”utf8″,”utf16le”,”ucs2″,”base64″,”latin1″, ”binary”, ”hex”)

 Eg : Create a buffer of length 20, with initializing all the value to fill as 0 in hexadecimal format

Node.js fs (File System) Module


• The fs module provides a lot of very useful functionality to access and interact with the file
system.
 There is no need to install it. Being part of the Node.js core, it can be used by simply requiring it:
 const fs = require('fs')
• This module provides a wrapper for the standard file I/O operations.
• All the methods in this module has asynchronous and synchronous forms.
 synchronous methods in this module ends with 'Sync'. For instance renameSync() is the synchronous
method for rename() synchronous method.
 The asynchronous form always take a completion callback as its last argument.
 The arguments passed to the completion callback depend on the method, but the first argument is
always reserved for an exception. If the operation was completed successfully, then the first argument
will be null or undefined.

 When using the synchronous form any exceptions are immediately thrown. You can use try/catch to
handle exceptions or allow them to bubble up.

Asynchronous method is preferred over synchronous method because it never blocks the program
execution where as the synchronous method blocks.
Node.js File System
• Node fs module provides an API to interact with FileSystem and to perform some IO
operations like create a file, read a File, delete a File etc..
 fs module is responsible for all the async or synchronous file I/O operations.

Node.js File System


• fs.readFile(fileName [,options], callback) : read the physical file asynchronously.
• fs.writeFile(filename, data [, options], callback) : writes data to a file
• fs.appendFile(): appends the content to an existing file
• fs.unlink(path, callback); delete an existing file
var fs = require("fs")
fs.unlink("test1.txt", function(err){
if(err) console.log("Err : " , err);
console.log("delete successful")
})

• fs.exists(path, callback) : determines if specified file exists or not


• fs.close(fd, callback(err));
• fs.rename(oldPath, newPath, callback): rename a file or folder

fs.rename("src.json", "tgt.json", err => {


if (err) {
return console.error(err)
}
console.log('Rename operation complete.');
});
Node.js File System
• The exists() and existsSync() methods are used to determine if a given path exists.
• Both methods take a path string as an argument.
 If existsSync() is used, a Boolean value representing path’s existence is returned.
 If exists() is used, the same Boolean value is passed as an argument to the callback function.

var fs = require("fs");
var path = "/";

fs.exists(path, function(exists) {
if (exists)
console.log(path + " exists: " + exists);
else
console.error("Something is wrong!");
});

• Reading Directories
 We can use the fs.readdir() method to list all the files const fs = require('fs')
and directories within a specified path: fs.readdir('./', (err, files) => {
if (err) {
console.error(err)
return
}
console.log('files: ', files)
})

Node.js File System


• fs.open(path, flags[, mode], callback) : opens a file for reading or writing in async
 path - string having file name including path.
 flags - tells the behavior of the file to be opened
 mode - sets the file mode; defaults to 0666, readable and writeable.
 callback - function which gets two arguments (err, fd).

// Asynchronous - Opening File


console.log("Going to open file!");
fs.open(test.txt', 'r+', function(err, fd) {
if (err) {
return console.error(err);
}
console.log("File opened successfully!");
});
Node.js File System
• fs.read(fd, buffer, offset, length, position, callback) : reads an opened file; from the file
specified by fd.
 fd <Integer> - is a file descriptor, a handle, to the file
 buffer <String> | <Buffer> : buffer into which the data will be read
 offset <Integer> : offset in the buffer to start reading at.
 length <Integer> : specifies the number of bytes to read
 position <Integer> : specifies where to begin reading from in the file
 callback (err, bytesRead)

• fs.write(fd, string[, position[, encoding]], callback): write into an opened file; specified by fd
• Alternatively :fs.write(fd, buffer[, offset[, length[, position]]], callback)

 offset : offset in the buffer to start writing at


 length : specifies the number of bytes to write.
 position : specifies where to begin writing
 The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how
many bytes were written from buffer.

Example : read file and write to file

• __filename, is the absolute path of the


currently executing file.
• __dirname is the absolute path to the
directory containing the currently
executing file
File System
• fs.stat(path, callback) : gets the information about file on path
o callback function gets two arguments (err, stats) where stats is an object of fs.Stats type

File System : example


URL Core module
• The url module provides utilities for URL resolution and parsing.
 It splits up a web address into readable parts.

var url = require('url');


//var adr = 'http://localhost:8080/MyApp/welcome.html?year=2017&month=february';
var adr = 'http://someserver.com/processLogin.jsp?username=soha&password=secret';

var q = url.parse(adr, true); //Parse an address

console.log("Host : " , q.host); //returns 'someserver.com'


console.log("Pathname : " , q.pathname); //returns '/processLogin.jsp'
console.log("Search : " , q.search); //returns '?username=soha&password=secret'
console.log("Href : " , q.href); //returns 'http://someserver.com/processLogin.jsp?username=soha
&password=secret'
console.log("Protocol : " , q.protocol); //returns 'http:'

var qdata = q.query; //returns an object: { year: 2017, month: 'february' }


console.log(qdata); //returns '{ username: 'soha', password: 'secret' }'
console.log(qdata.username, qdata.password); //returns 'soha secret'

URL Core module


var http = require('http');
var url = require('url');
var fs = require('fs');
function process_request(req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
}

var s = http.createServer(process_request);
s.listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Web development with Node : http.ServerRequest
• When listening for request events, the callback gets an http.ServerRequest object as the
first argument (function(req,res))
• This object contains some properties:
 req.url: This property contains the requested URL as a string
o It does not contain the schema, hostname, or port, but it contains everything after that.
o Eg : if URL is :http://localhost:3000/about?a=20 then req.url will return /about?a=20
 req.method: This contains the HTTP method used on the request. It can be, for example, GET,
POST, DELETE, or HEAD.
 req.headers: This contains an object with a property for every HTTP header on the request.

 Eg : Serving file on request : Reading a file at server end and serving to browser!

Serving file on request <!-- summer.html -->


<html>
<head>
<title>Hello there</title>
var http = require('http');
</head>
var url = require('url');
<body>
var fs = require('fs');
<h3>Welcome to Node!
Its summer now</h3>
http.createServer(function (req, res) {
</body>
var q = url.parse(req.url, true);
./summer.html </html>
var filename = "." + q.pathname;

fs.readFile(filename, function(err, data) {


if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(3000); //invoke as http://localhost:3000/summer.html+
Routing
• Routing refers to the mechanism for serving the client the content it has asked

<html>
var http = require('http'); <body>
var url = require('url'); <h1>Login</h1>
var fs = require('fs'); <form action="process">
Radius : <input name="radius">
function process_req(req, res) { <input type="submit"
if (req.method == 'GET' && req.url == '/') { value="Calc Radius">
fs.readFile('radius.html', function(err, data) { </form>
res.writeHead(200, {'Content-Type': 'text/html'}); </body></html>
res.write(data);
res.end();
});
}
else if(req.method == 'GET' && req.url.substring(0,8) == '/process'){
var q = url.parse(req.url, true);
var qdata = q.query;
var r = qdata.radius;
{ radius: '100' }
var rad = Math.PI + r * r;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The area is : " + rad);
res.end();
}
else
res.end("not found");
}
var server = http.createServer(process_req)
server.listen(3000);
console.log('server listening on localhost:3000');
<body> //loginpost.html
var http = require('http'); <h1>Login</h1>
var fs = require('fs'); <form action="processlogin"
method="post">
function process_req(req, res) { Username :
if (req.method == 'GET' && req.url == '/') { <input name="uname"><br>
fs.readFile('loginPost.html', function(err, data) { Password :
res.writeHead(200, {'Content-Type': 'text/html'}); <input type="password"
res.write(data); name="passwd"><br>
res.end(); <input type="submit"
}); value="login">
} </form>
else if(req.method == 'POST'){ </body>
var body = "";
req.on("data",function(data){
body += data;
res.writeHead(200, {'Content-Type': 'text/html'});
var arr = body.split("&");
res.write("Welcome " + arr);
res.end();
})
}
}
var server = http.createServer(process_req)
server.listen(3000);
console.log('server listening on localhost:3000');

Promise
• Promises are a new feature of ES6.
 It’s a method to write asynchronous code; it represents the completion of an asynchronous function.
 It is a Javascript object that might return a value in the future.
 It accomplishes the same basic goal as a callback function, but with many additional features and a
more readable syntax.
• Creating a Promise
 Promises are created by using a constructor called Promise and passing it a function that receives two
parameters, resolve and reject, which allow us to indicate to it that it was resolved or rejected.

let promise = new Promise(function(resolve, reject) {


// executor code - things to do to accomplish your promise
});

let promise = new Promise(function(resolve, reject) {


// things to do to accomplish your promise

if(/* everything turned out fine */) {


resolve('Stuff worked')
} else { // for some reason the promise doesn't fulfilled
reject(new Error('it broke'))
}
})
Consuming a Promise
• The promise we created earlier has fulfilled with a value, now we want to be able to access
the value.
• Promises have a method called then() that will run after a promise reaches resolve in the
code.
• The then() method returns a Promise. It takes up to two arguments: callback functions for
the success and failure cases of the Promise.
• Syntax : p.then(onFulfilled[, onRejected]);
 onFulfilled function called if the Promise is fulfilled. This function has one argument, the fulfillment
value.

 Example promise.then(
function(result) { /* handle a successful result */ },
function(error) { /* handle an error */ }
);

promise.then(function(result) {
console.log("Promise worked");
}, function(err) {
console.log("Something broke");
});

Consuming a Promise
 Full example

const promise = new Promise((resolve, reject) => {


if(true)
resolve("resolved!!")
});

promise.then(msg => console.log("In then - "+ msg))

let promise = new Promise(function(resolve, reject) {


setTimeout(() => resolve("done!"), 3000);
});

// resolve runs the first function in .then


promise.then(
result =>console.log(result), //shows "done!" after 3 seconds
error =>console.log(error) // doesn't run
);

let promise = new Promise(function(resolve, reject) {


setTimeout(() => reject(new Error("Whoops!")), 1000);
});

// reject runs the second function in .then


promise.then(
result => alert(result), // doesn't run
error => alert(error) // shows "Error: Whoops!" after 1 second
);
Consuming a Promise
• Alternatively, instead of using this syntax of then(fulfilled, rejected), you can
also use catch()
• The then and catch handlers are asynchronous.
 Basically, then and catch will be executed once Javascript finished reading the code

promise.then(function(result) { const promise = new Promise((resolve, reject) => {


console.log(result) // Note: only 1 param allowed
}).catch(function(err) { return reject(‘Hi')
console.log(err) })
})
// Parameter passed into reject would be the arguments passed into
console.log('Hello world') catch.
promise.catch(err => console.log(err)) // Hi

function randomDelayed(max = 10, expected = 5, delay = 1000) {


return new Promise((resolve, reject) => {
const number = Math.floor(Math.random() * max)

setTimeout(
() => number > expected
? resolve(number)
: reject(new Error('lower than expected number')), 1000
);
});
}
randomDelayed(100, 75, 2500)
.then(number => console.log(number))
.catch(error => console.error(error.toString()));

Chained Promises
• The methods promise.then(), promise.catch(), and promise.finally() can be used to associate
further action with a promise that becomes settled.
 Each .then() returns a newly generated promise object, which can optionally be used for chaining

const myPromise = new Promise((resolve, reject) => { import fs from 'fs';


setTimeout(() => {
resolve('foo'); function readAFile(path) {
}, 300); return new Promise((resolve, reject) => {
}); fs.readFile(path, 'utf8', (error, data) => {
if (error) return reject(error);
myPromise return resolve(data);
.then(handleResolvedA, handleRejectedA) });
.then(handleResolvedB, handleRejectedB) });
.then(handleResolvedC, handleRejectedC); }

const myPromise = new Promise((resolve) => { readAFile('./file.txt')


setTimeout(() => { .then(data => console.log(data))
resolve('foo'); .catch(error => console.error(error));
}, 300);
});
function myAsyncFunction(url) {
myPromise return new Promise((resolve, reject) => {
.then((x)=>{console.log("in A - " + x);}) const xhr = new XMLHttpRequest()
.then((x)=>{console.log("in B - " + x);}) xhr.open("GET", url)
.then((x)=>{console.log("in C - " + x);}); xhr.onload = () => resolve(xhr.responseText)
xhr.onerror = () => reject(xhr.statusText)
xhr.send()
});
}
Ajax example with promise
• You'll see Promises used a lot when fetching data from an API
<!DOCTYPE html>
<html> • Promises can be confusing, both for new developers and
<body> experienced programmers that have never worked in an
<div id="msg"></div> asynchronous environment before.
<button id="btnGet">Get Message</button> • However, it is much more common to consume promises than
</body> create them. Usually, a browser’s Web API or third party library
</html> will be providing the promise, and you only need to consume it

function load(url) {
return new Promise(function (resolve, reject) {
const request = new XMLHttpRequest();
request.onreadystatechange = function (e) {
if (this.readyState === 4) {
if (this.status == 200) {
resolve(this.response);
} else {
reject(this.status);
btn.onclick = function () {
}
load('data.json')
}
.then(
}
response => {
request.open('GET', url, true);
const result = JSON.parse(response);
request.send();
$(“#msg”).text(result.message);
});
},
}
error => $(“#msg”).text(`Error getting message,
HTTP status: ${error}`
);
}

Using Fetch
• One of the most useful and frequently used Web APIs that returns a promise is the
Fetch API.
 It allows you to make an asynchronous resource request over a network.
 fetch() is a two-part process, and therefore requires chaining then()

// Fetch a user from the GitHub API


fetch('https://api.github.com/users/octocat')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
})
.catch((error) => {
console.error(error)
})
async/await
• async/await added in ECMAScript 2017 (ES8)
• async/await is built on promises
• async keyword put in front of a function declaration turns it into an async function
• An async function is a function that knows how to expect the possibility of the await keyword
being used to invoke asynchronous code.
 We use the async keyword with a function to represent that the function is an asynchronous function.
 The async function returns a promise.

//simple synchromous JS function and invocation


function hello() { return "Hello" };
hello();

//converting above JS function into async function


async function hello() { return "Hello" };
hello();

// You can also create an async function expression like this:


let hello = async function() { return "Hello" };
hello();

//you can also use arrow functions:


let hello = async () => { return "Hello" };

async/await
• To consume the value returned when the promise fulfills (since it is returning a promise) use a
.then() block

hello().then((value) => console.log(value))


//or even just shorthand such as
hello().then(console.log)

//complete example
async function hello(){
return "hello-1"
}
hello().then((x)=>console.log(x))
// returns"hello-1"

let f = async () => {


console.log('Async function.');
return Promise.resolve("Hello-1"); //function returns a promise
}

f().then(function(result) {
console.log(result)
});
The await keyword
• The await keyword is used inside the async function to wait for the asynchronous operation
 await can be put in front of any async promise-based function to pause your code on that line until the
promise fulfills, then return the resulting value.
 Syntax: let result = await promise;
 You can use await when calling any function that returns a Promise, including web API functions

// a promise
let promise = new Promise(function (resolve, reject) { function logFetch(url) {
setTimeout(function () { return fetch(url)
resolve('Promise resolved')}, 4000); .then(response => response.text())
}); .then(text => {
console.log(text);
}).catch(err => {
async function asyncFunc() {// async function console.error('fetch failed', err);
});
// wait until the promise resolves }
let result = await promise;
async function logFetch(url) {
console.log(result); try {
console.log('hello'); const response = await fetch(url);
} console.log(await response.text());
}
asyncFunc(); // calling the async function catch (err) {
console.log('fetch failed', err);
}
}

Next gen Javascript


• const : from JS 1.5 onwards.- to define constants
 Eg :
const myBirthday = '18.04.1982';
myBirthday = '01.01.2001'; // error, can't reassign the constant!

const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go'];


LANGUAGES = "Javascript"; // shows error.
LANGUAGES.push('Java'); // Works fine.
console.log(LANGUAGES); // ['Js', 'Ruby', 'Python', 'Go', 'Java']

• let : to define block-scoped variables; can be used in four ways:


 as a variable declaration like var; in a for or for/in loop, as a substitute for var;
 as a block statement, to define new variables and explicitly delimit their scope
 to define variables that are scoped to a single expression.
let a = 50; let b = 100;
 Eg : let message = 'Hello!'; if (true) {
 Eg : let user = 'John', age = 25, message = 'Hello'; let a = 60;
var c = 10;
if (true) { console.log(a/c); // 6
let a = 40; console.log(b/c); // 10
console.log(a); //40 }
} console.log(c); // 10
console.log(a); // undefined console.log(a); // 50
Next gen Javascript
• Arrow functions : same as lambda in TS

Next gen Javascript


• Exports and imports
Next gen Javascript : Classes, properties and methods

constructor method is
always defined with
the name "constructor"

Classes can have methods,


which defined as functions,
albeit without needing to use
the function keyword.

Next gen Javascript : Classes, properties and methods


• To declare a class, you use the class keyword with the name of the class
• There can only be one "constructor" in a class; SyntaxError will be thrown if the class
contains more than one occurrence of a constructor method.

class Rectangle { class Rectangle {


constructor(height, width) { constructor(height, width) {
this.height = height; this.height = height;
this.width = width; this.width = width;
} }
}
// Method
calcArea() {
return this.height * this.width;
}
}

const square = new Rectangle(10, 10);

console.log(square.calcArea()); // 100
Next gen Javascript : Spread and rest operators
• spread:

• rest operator : used to merge a list of function arguments into an array

Next gen Javascript


• Destructuring : allows to easily extract array elements or object properties and store
them in variables
 Destructuring is useful because it allows you to do in a single line, what would otherwise require
multiple lines

var rect = { x: 0, y: 10, width: 15, height: 20 };

// Destructuring assignment
var {x, y, width, height} = rect;
console.log(x, y, width, height); // 0,10,15,20

rect.x = 10;

// assign to existing variables using outer parentheses


({x, y, width, height} = rect);
console.log(x, y, width, height); // 10,10,15,20

const arr=[1,2,3,4,5]
var [a,b] = arr
console.log(a,b) //1,2
Array functions
• Array.filter
 You can filter arrays by using the .filter(callback) method.
 The result will be another array that contains 0 or more elements based on the condition (or the
"check") that you have in the callback.

var nums = [1, 2, 3, 21, 22, 30];


var evens = nums.filter(i => i % 2 == 0);

const grades = [10, 2, 21, 35, 50, -10, 0, 1];

//get all grades > 20


const result = grades.filter(grade => grade > 20); // [21, 35, 50];

// get all grades > 30


grades.filter(grade => grade > 30); // ([35, 50])

Array functions
• Array.map() : returns a new array containing the result of invoking the callback
function for every item in the array.

var numbers = [1, 4, 9];


var roots = numbers.map(Math.sqrt);
console.log("roots is : " + roots ); //1,2,3

var numbers = [1, 2, 3, 4];


var doubled = numbers.map(i => i * 2);
var doubled = [for (i of numbers) i * 2]; //same as above
console.log(doubled); // logs 2,4,6,8
Reference and primitive types

Next gen Javascript


• Template strings provide us with an alternative to string concatenation. They also allow
us to insert variables into a string.
 Traditional string concatenation uses plus signs or commas to compose a string using variable
values and strings.
 console.log(lastName + ", " + firstName + “ “ + middleName)

• With a template, we can create one string and insert the variable values by surrounding
them with ${variable}.
 console.log(`${lastName}, ${firstName} ${middleName}`)
 Any JavaScript that returns a value can be added to a template string between the ${ } in a
template string.
//Javascript : generating an html string
var msg1 = 'Have a great day';
var html = '<div>' + msg1 + '</div>';
document.write(html)

//Using template strings


var msg2 = 'Never give up';
var html1 = `<div>${msg2}</div>`;
document.write(html1)
BOOTSTRAP 4
Pre-reqs:
• HTML
• CSS
• JavaScript

Introduction
• Bootstrap is an opensource frontend framework developed by Twitter.
 It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first
web sites.
 Bootstrap is a free and open source collection of tools for creating websites and web applications.
 Bootstrap contains a set of CSS- and HTML-based templates for styling forms, elements, buttons,
navigation, typography, and a range of other UI components.
 It also comes with optional JavaScript plugins to add interactivity to components.

• Bootstrap is promoted as being One framework, every device.


 This is because websites built with Bootstrap will automatically scale between devices — whether the
device is a mobile phone, tablet, laptop, desktop computer, screen reader, etc.

• Responsive web design is about creating web sites which automatically adjust themselves
to look good on all devices, from small phones to large desktops.
 Developers can then create a single design that works on any kind of device: mobiles, tablets, smart
TVs, and PCs
Where to Get Bootstrap 4?
• There are two ways to start using Bootstrap 4 on your own web site.
 Download Bootstrap 4 from getbootstrap.com : https://getbootstrap.com/docs/4.5/getting-
started/download/
 If you don't want to download and host Bootstrap 4 yourself, you can include it from a CDN (Content
Delivery Network).
 MaxCDN provides CDN support for Bootstrap's CSS and JavaScript. You must also include jQuery
 The https://getbootstrap.com/docs/4.5/getting-started/introduction/ page gives CDN links for CSS and
js files

<!-- Latest compiled and minified CSS -->


<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<!-- jQuery library -->


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Popper JS -->


<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<!-- Latest compiled JavaScript -->


<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

Create First Web Page With Bootstrap 4

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap 4 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">
</script>
</head>
<body>
//body comes here
</body>
</html>
To ensure proper rendering and touch zooming, add this <meta> tag
• The width=device-width part sets the width of the page to follow the
screen-width of the device (which will vary depending on the device).
• The initial-scale=1 part sets the initial zoom level when the page is first
loaded by the browser.
Create First Web Page With Bootstrap 4
• Bootstrap 4 also requires a containing element to wrap site contents.
• There are two container classes to choose from:
 The .container class provides a responsive fixed width container
 The .container-fluid class provides a full width container, spanning the entire width of the
viewport

Bootstrap Container
• Bootstrap container is basically used in order to create a centered area that lies within the
page and generally deals with the margin of the content and the behaviors that are
responsible for the layout.
 It contains the grid system (row elements, which in turn are the container of columns).
• There are two container classes in Bootstrap:
 .container: provides a fixed width container with responsiveness. It will not take the complete width of
its viewport.
 .container-fluid: provides a full width container of the viewport and its width will change (expand or
shrink) on different screen sizes.
<body>
<div class="container">
<h1>Container</h1>
</div>
</body>
Bootstrap Grid System
• Bootstrap grid system divides the screen into columns―up to 12 in each row. (rows are
infinite)
 The column widths vary according to the size of screen they're displayed in.
 Bootstrap's grid system is responsive, as the columns resize themselves dynamically when the
size of browser window changes.
 If you do not want to use all 12 columns individually, you can group the columns together to
create wider columns
 it is a good practice to wrap all the contents within a container; create a row (with class row)
inside a container, then start creating the columns.

<div class="container">
<div class="row">
//add desired number of cols here
</div>
</div>

Grid Classes
• The Bootstrap 4 grid system has five classes:
 .col- (extra small devices - screen width less than 576px)
 .col-sm- (small devices - screen width equal to or greater than 576px)
 .col-md- (medium devices - screen width equal to or greater than 768px)
 .col-lg- (large devices - screen width equal to or greater than 992px)
 .col-xl- (xlarge devices - screen width equal to or greater than 1200px)

Example
Building a Basic Grid

MISC COMPONENTS
<h1> - <h6>
• Typography refers to the various styles present in Bootstrap style sheets which define how
various text elements will appear on the web page.
 HTML uses default font and style to create headings, paragraphs, lists and other inline elements.
 Bootstrap overrides default and provides consistent styling across browsers for common typographic
elements.
• Bootstrap 4 styles HTML headings (<h1> to <h6>) with a bolder font-weight and an increased
font-size

• Additionally, you can use the <small> tag with .text-muted class to display the secondary text
of any heading in a smaller and lighter variation.

Working with Paragraphs


• Bootstrap's global default font-size is 1rem (typically 16px), with a line-height of 1.5. This is
applied to the <body> and all paragraphs
 You can also make a paragraph stand out by adding the class .lead on it.
 You can also transform the text to lowercase, uppercase or make them capitalize.

• Text Coloring
 Colors are the powerful method of conveying important information in website design.
Tables
• Bootstrap provides an efficient layout to build elegant tables
 You can create tables with basic styling that has horizontal dividers and small cell padding, by just adding
the Bootstrap's class .table to the <table> element.

 The .table-striped class adds zebra-stripes to a table


 The .table-bordered class adds borders on all sides of the table and cells
 The .table-condensed class makes a table more compact by cutting cell padding in half
 The .table-dark class create inverted version of this table, i.e. table with light text on dark backgrounds
<table class="table table-dark">

Jumbotron
• A jumbotron indicates a big box for calling extra attention to some special content or
information.
 A jumbotron is displayed as a grey box with rounded corners. It also enlarges the font sizes of
the text inside it.
 Just wrap your featured content like heading, descriptions etc. in a <div> element and apply the
class .jumbotron on it.
 Tip: Inside a jumbotron you can put nearly any valid HTML, including other Bootstrap
elements/classes.

<div class="jumbotron">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS, and JS framework for
developing responsive, mobile-first projects on the web.</p>
</div>
images
• To add images on the webpage use element <img> , it has three classes to apply
simple styles to images.
 .img-rounded : To add rounded corners around the edges of the image, radius of the border is
6px.
 .img-circle : To create a circle of radius is 500px
 .img-thumbnail : To add some padding with grey border , making the image look like a polaroid
photo.

<img src="taj.jpg" class="img-rounded"> <!-- rounded edges-->


<img src="taj.jpg." class="img-circle"> <!-- circle -->
<img src="taj.jpg" class="img-thumbnail"> <!-- thumbnail -->

Bootstrap 4 Icons
• Bootstrap 4 does not have its own icon library; but there are many free icon libraries to
choose from, such as Font Awesome and Google Material Design Icons
 To use Font Awesome icons, add the following CDN link to your HTML page
 <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"
integrity="sha384-
UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/"
crossorigin="anonymous">
<i class="fas fa-cloud"></i>
<i class="fas fa-coffee"></i>
<i class="fas fa-car"></i>
<i class="fas fa-file"></i>
<i class="fas fa-bars"></i>
Alerts
• Bootstrap comes with a very useful component for displaying alert messages in various
sections of our website
 You can use them for displaying a success message, a warning message, a failure message, or an
information message.
 These messages can be annoying to visitors, hence they should have dismiss functionality added to
give visitors the ability to hide them.

<div class="alert alert-success"> contextual classes for alert messages:


Amount has been transferred successfully. alert-success, alert-info, alert-danger,
</div> alert-warning

<div class="alert alert-success alert-dismissable">


<button type="button" class="close" data-dismiss="alert">&times;</button>
Amount has been transferred successfully.
</div>

dismissible alert box

Bootstrap Lists
• Unstyled Ordered and Unordered Lists
 Sometimes you might need to remove the default styling form the list items. You can do this by simply
applying the class .list-unstyled to the respective <ul> or <ol> elements

• If you want to create a horizontal menu using ordered or unordered list you need to place all
list items in a single line i.e. side by side.
 You can do this by simply applying the class .list-inline to the respective <ul> or <ol>, and the class .list-
inline-item to the <li> elements.
Page Components : List Group
• List group is used for creating lists; eg a list of useful resources or a list of recent activities
 Add class list-group to a <ul> or <div> element to make its children appear as a list.
 The children can be li or a element, depending on your parent element choice.
 The child should always have the class list-group-item.

Page Components : List Group


• We can display a number beside each list item using the badge component.
 Add this inside each “list-group-item” to display badge; badges align to the right of each list item

• We can also apply various colors to each list item by adding list-group-item-*
classes along with list-group-item.
Bootstrap 4 Navs
• Navs : a group of links placed inline with each other to be used for navigation.
 There are options to make this group of links appear either as tabs or small buttons, the latter known
as pills in Bootstrap.
 If you want to create a simple horizontal menu, add the .nav class to a <ul> element, followed by
.nav-item for each <li> and add the .nav-link class to their links:

 Add the class .nav-tabs to the basic nav to generate a tabbed navigation.
 Similarly, you can create pill based navigation by adding the class .nav-pills on the basic nav instead
of class .nav-tabs
 Vertically stack these pills by attaching an additional class flex-column

Toggleable / Dynamic Pills


• To make the tabs toggleable, add the data-toggle="tab" attribute to each link.
 Then add a .tab-pane class with a unique ID for every tab and wrap them inside a <div> element with
class .tab-content.

• To fade the tabs in


and out when
clicking on them,
add the .fade class
to .tab-pane
Navs with dropdown
• You can add dropdown menus to a link inside tabs and pills nav with a little extra markup.
 The four CSS classes .dropdown, .dropdown-toggle, .dropdown-menu and .dropdown-item are
required

Navbar
• A navbar is a navigation header that is placed at the top of the page
 A standard navigation bar is created with the .navbar class, followed by a responsive collapsing class:
.navbar-expand-xl|lg|md|sm
 To add links inside the navbar, use a <ul> element with class="navbar-nav".
 Then add <li> elements with a .nav-item class followed by an <a> element with a .nav-link class

Remove .navbar-expand-xl|lg|md|sm class to create a vertical nav bar


Navbar
• Brand / Logo
 The .navbar-brand class is used to highlight the brand/logo/project name of your page

<a href="#" class="navbar-brand">


<img src="paws.png" height="28" alt="CoolBrand">
</a>

• Collapsing The Navigation Bar


 Very often, especially on small screens, you want to hide the navigation links and replace them with a
button that should reveal them when clicked on.
 To create a collapsible navigation bar, use a button with class="navbar-toggler", data-toggle="collapse"
and data-target="#thetarget".
 Then wrap the navbar content (links, etc) inside a div element with class="collapse navbar-collapse",
followed by an id that matches the data-target of the button: "thetarget".

<!-- Toggler/collapsibe Button -->


<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">

Navbar
Standing Out : Buttons
• Its easy to convert an a, button, or input element into a fancy bold button in Bootstrap; just
have to add the btn class

 You can also create outline buttons by replacing the button modifier classes

 Buttons come in various color options:  And in various sizes:


o btn-default for white o btn-lg for large buttons
o btn-primary for dark blue o btn-sm for small buttons
o btn-success for green o btn-xs for extra small button
o btn-info for light blue
o btn-warning for orange
o btn-danger for red

<button type="button" class="btn btn-primary btn-lg">Large button</button>


<button type="button" class="btn btn-primary">Default button</button>
<button type="button" class="btn btn-primary btn-sm btn-success">Small button</button>
Creating Forms
• Bootstrap provides three different types of form layouts:
 Vertical Form (default form layout) Eg ->
 Horizontal Form
 Inline Form

• Standard rules for all three form layouts:


 Wrap labels & form controls in <div class="form-group">
(for optimum spacing)
 Add class .form-control to all textual <input>, <textarea>,
and <select> elements

<form class="form">
<div class="form-group">
<label for=“n1">Name</label>
<input type="text" class="form-control" id=“n1“ placeholder="Your Name" />
</div>
</form>

class form-control in an
input element will make it a
full-width element

Creating Forms : Vertical Form Layout


 This is the default Bootstrap form layout in which styles are applied to form controls without adding any
base class to the <form> element or any large changes in the markup.
 The form controls in this layout are stacked with left-aligned labels on the top.
Creating Forms : Horizontal Form Layout
 Labels and form controls are aligned side-by-side using the Bootstrap grid classes.
 To create this layout add the class .row on form groups and use the .col-*-* grid classes to specify the
width of your labels and controls.

Creating Forms : Inline Form Layout


• Additional rule for an inline form: Add class .form-inline to the <form> element
EXPRESS.JS
Node.js web application framework

Introduction
• If you write serious apps using only core Node.js modules you most likely find
yourself reinventing the wheel by writing the same code continually for similar
tasks, such as the following:
 Parsing of HTTP request bodies and Parsing of cookies
 Managing sessions
 Organizing routes with a chain of if conditions based on URL paths and HTTP methods of
the requests
 Determining proper response headers based on data types

• Express is a web application framework for Node


 Its built on top of Node.js.
 It provides various features that make web application development fast and easy
compared to Node.js.
Express.js Installation
• Create a new folder: eg E:\Express-app
• E:\Express-app>npm init //for creating package.json
• E:\Express-app>npm install express --save

{
"name": "express-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}

First app
• An Express app is created by calling the express() function
 express() : Creates an Express application; is a top-level function exported by the
express module
 The app object conventionally denotes the Express application.
 This object, which is traditionally named app, has methods for routing HTTP requests,
configuring middleware, rendering HTML views, registering a template engine, and
modifying application settings that control how the application behaves

let express = require("express") // import the express module

let app = express() // create an Express application

app.get("/",function(req,resp){
resp.send("Hello world")
})

app.listen(3000, function(){
console.log("app running on port 3000")
})

The app.listen() method returns an http.Server object


Express Routes
• HTTP verb and URL combinations are referred to as routes, and Express has
efficient syntax for handling them.
Open browser and type:
var express = require("express"); http://localhost:3000
var http = require("http"); http://localhost:3000/foo
var app = express(); http://localhost:3000/bar
http://localhost:3000/admin - gives error
app.get("/", function(req, res, next) {
res.send("Hello <strong>home page</strong>");
});

app.get("/foo", function(req, res, next) {


res.send("Hello <strong>foo</strong>");
});

app.get("/bar", function(req, res, next) {


res.send("Hello <strong>bar</strong>");
});
//app is passed to the http.createServer() method

http.createServer(app).listen(8000);

Express Routes
• If none of your routes match the request, you'll get a "Cannot GET <your-
request-route>" message as response.

• This message can be replaced by a 404 not found page using this simple route

app.get('*', function(req, res){


res.send('Sorry, this is an invalid URL.');
});

app.get(‘/course/:id', function(req, res){


var course = //code to retrieve course
If(!course){
res.status(404).send(“course not found”);
});
Routing basics
app.get("/", function(req, res, next) {
res.send("Hello <strong>home page</strong>");
});

• The get() method defines routes for handling GET requests.


• Express also defines similar methods for the other HTTP verbs (put(), post(),
delete(), and so on).
 app.method(path, handler) : This METHOD can be applied to any one of the HTTP
verbs – get, post, put, delete.
 All methods take a URL path and a sequence of middleware as arguments.
 The path is a string or regular expression representing the URL that the route
responds to. Note that the query string is not considered part of the route’s URL.
• Also notice that we haven’t defined a 404 route, as this is the default behavior
of Express when a request does not match any defined routes.

Routing basics
app.get("/", function(req, res, next) {
res.send("Hello <strong>home page</strong>");
});

• Express also augments the request and response objects with additional
methods. Example response.send() .
 send() is used to send a response status code and/or body back to the client.
 If the first argument to send() is a number, then it is treated as the status code. If a
status code is not provided, Express will send back a 200.
 The response body can be specified in the first or second argument, and can be a string,
Buffer, array, or object.

• send() also sets the Content-Type header unless you do so explicitly.


 If the body is a string, Express will set the Content-Type header to text/html.
 If the body is an array or object, then Express will send back JSON.
 If the response body is a Buffer, the Content-Type header is also set to application/octet-
stream
Routing basics
var express = require("express");
var app = express();
var path = require('path');

app.get("/buff", function(req, res, next) {


var buff = Buffer.from("Hello World");
res.send(buff.toString());
});
app.get("/string", function(req, res, next) {
res.send("Hello <strong>String response</strong>");
});
app.get("/json", function(req, res, next) {
res.send({name:'Soha',age:23});
});
app.get("/array", function(req, res, next) {
res.send(['NodeJS','Angular','ExpressJS']);
});
app.get("/file", function(req, res, next) {
res.sendFile(path.join(__dirname + '/summer.html'));
});
app.listen(3000);

Route Parameters
• Route can be parameterized using a regular expression

var express = require("express");


var http = require("http");
Ignore multiple slash
var app = express();
app.get(/\/products\/([^\/]+)\/?$/, function(req, res, next) {
res.send("Requested " + req.params[0]);
});
http.createServer(app).listen(8000);

/products?productId=sweater
/products/sweater

The above regular expression matches anything but /


/products/books
/products/books:aaa
/products/books/
/products/books?aaa
/products/books=aaa

Doesn’t match:
/products/books/aaa
/products/books//
/products//
Eg 2 : Using regular expressions to match routes
 Assume you want to match things like /users/123 or /users/456 but not /users/anita. You
can code this into a regular expression and also grab the number

app.get(/^\/users\/(\d+)$/, function(req, res) {


var userId = parseInt(req.params[0], 10);
res.send("Requested " + userId);
});

• req.params - An object containing parameter values parsed from the URL path.
 For example, if you have the route /user/:name, then the “name” property is available
as req.params.name. This object defaults to {}.
 GET /user/shrilata
 req.params.name // => “shrilata“

 When you use a regular expression for the route definition, each capture group match
from the regex is available as req.params[0], req.params[1]
 GET /file/javascripts/jquery.js
 req.params[0] // => "javascripts/jquery.js"

Route Parameters
• One of the most powerful features of routing is the ability to use placeholders to
extract named values from the requested route, marked by the colon ( :)
character.
 When the route is parsed, express puts the matched placeholders on the req.params
object for you.

app.get('/user/:id', function(req, res) { Placeholders match any


res.send('user ' + req.params.id); sequence of characters except for
}); forward slashes.

app.get(‘/product/:prodname', function(req, res) {


res.send(‘Product : ' + req.params.prodname);
});
Route Parameters
 Below example, creates a named parameter productId.

app.get("/product/:productId(\\d+)", function(req, res, next) {


res.send("Requested " + req.params.productId );
});

productId can now only be made up of digits


Invoke as : http://localhost:3000/product/123

app.get('/users/:userId/books/:bookId', function (req, res) {


res.send(req.params)
//res.send(req.params.userId + ":" + req.params.bookId)
})
//Route path: /users/:userId/books/:bookId
//Request URL: http://localhost:3000/users/34/books/8989
//req.params: { "userId": "34", "bookId": "8989" }

Working with parameters using get


• req.query
 Express parses query string parameters by default, and puts them into the req.query
property.
 If the request is GET /search?username=Shrilata
req.query.username returns “Shrilata"

 Lets say the incoming url is : http://localhost:3000/add?no1=10&no2=20


 Use req.query to query the request parameters

app.get("/add", function (req, res) {


n1 = parseInt(req.query.no1);
n2 = parseInt(req.query.no2);
res.end("Addition : " + (n1 + n2) );
});
Handle GET Request

Multiple different methods


• We can also have multiple different methods at the same route.

var express = require('express');


var app = express();

app.get('/hello', function(req, res){


res.send("Hello World!");
});

app.post('/hello', function(req, res){


res.send("You just called the post method at '/hello'!\n");
});

app.delete('/hello', function(req, res){


res.send("You just called the delete method at '/hello'!\n");
});

app.listen(3000);
Handle POST Request
• To handle HTTP POST request in Express.js version 4 and above, you need
to install a middleware module called body-parser.
 This is used to parse the body of requests which have payloads attached to them.

 Install it using : npm install --save body-parser


 Mount it by including the following lines in your js

var bodyParser = require("body-parser");


app.use(bodyParser.urlencoded({ extended: false }));

 This body-parser module parses the JSON, buffer, string and url encoded data
submitted using HTTP POST request.
 Eg :To parse json data: app.use(bodyParser.json())

bodyParser.urlencoded(): Parses the text as URL encoded data (which is how


browsers tend to send form data from regular forms set to POST) and exposes the
resulting object (containing the keys and values) on req.body

Handle POST Request


Routing handlers
• app.get(path, callback [, callback ...])
 Routes HTTP GET requests to the specified path with the specified callback
functions. Callback functions can be:
o A middleware function.
o A series of middleware functions (separated by commas).
o An array of middleware functions.

 The next() function gives you the opportunity to do some additional examinations on
the incoming URL and still choose to ignore it

app.get('/example/b', f1 , f2 , f3);

……..
function f1(){
//handle the callback
next();
}

Routing handlers
//More than one callback function can handle a route
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})

//An array of callback functions can handle a route.


var cb0 = function (req, res, next) {
console.log('CB0')
next()
}

var cb1 = function (req, res, next) {


console.log('CB1')
next()
}

var cb2 = function (req, res) {


res.send('Hello from C!')
}
app.get('/example/c', [cb0, cb1, cb2])
Views, templates, template engines
• A template engine facilitates you to use static template files in your applications.
 At runtime, it replaces variables in a template file with actual values, and transforms the
template into an HTML file sent to the client.
 This approach makes it easier to design an HTML page.
 Some popular template engines that work with Express are Pug, Mustache, Haml,
Hogan, Swig and EJS.

• Using EJS:
1. install ejs : npm install ejs –save
2. Create a folder called “views” in main project folder

Views, templates, template engines


• Create a file called index.ejs and put it into the “views” directory
REACT.JS
JavaScript library for building user interfaces

What is React?
• From the official React page : A JavaScript library for building user interfaces
• Its not a framework; React does only one thing – create awesome UI!
• React is used to build single page applications.
• React.js is a JavaScript library. It was developed by engineers at Facebook.
• React is a declarative, efficient, and flexible JavaScript library for building
user interfaces.
• It lets you compose complex UIs from small and isolated pieces of code
called “components”.
Client-side Javascript frameworks
• Ember : was initially released in December 2011. It is an older framework that has
less users than more modern alternatives such as React and Vue
• Angular is an open-source web application framework led by the Angular Team at
Google and by a community of individuals and corporations.
• Vue : first released in 2014; is the youngest of the big four, but has enjoyed a recent
uptick in popularity.
• React : released by Facebook in 2013. By this point, FB had already been using
React to solve many of its problems internally.
 React itself is not technically a framework; it's a library for rendering UI components.
 React is used in combination with other libraries to make applications — React and React
Native enable developers to make mobile applications; React and ReactDOM enable them
to make web applications, etc.

Components
• A Component is one of the core building blocks of React.
• Its just a custom HTML element!

• Every application you will develop in React will be made up of pieces called
components.
 Components make the task of building UIs much easier. You can see a UI broken down
into multiple individual pieces called components and work on them independently and
merge them all in a parent component which will be your final UI.
Why react
• Created and maintained by facebook
• Has a huge community on Github
• Component based architecture
• React is fast. Apps made in React can handle complex updates and still feel
quick and responsive.
• React is modular. Instead of writing large, dense files of code, you can write
many smaller, reusable files. React’s modularity can be a beautiful solution to
JavaScript’s maintainability problems.
• React is scalable. Large programs that display a lot of changing data are
where React performs best.
• React is popular.
• UI state becomes difficult to manage with vanilla Javascript

Requirements
• Ensure that NodeJS and typescript are installed
 Install TypeScript as follows:
 npm install –g typescript
Using create-react app
• npx create-react-app my-app
• cd my-app
• npm start

Understanding the folder structure


Index.html

• The root node is the HTML


element where you want to
display the result.
• It is like a container for
content managed by React.
• It does NOT have to be a
<div> element and it does
NOT have to have the
id='root

Understanding the folder structure


Understanding JSX
import React from 'react';

function App() {
/*return (
<div >
<h2>Welcome to React!</h2>
</div>
);*/
return React.createElement('div',null,'h2','Hi, welcome to React');
}
export default App;

function App() {
/*return (
<div >
<h2>Welcome to React!</h2>
</div>
);*/
return React.createElement('div',null,
React.createElement('h1',{className:'App'},'Hi welcome to React'));
}
export default App;

Understanding JSX
• Eg : const mytag = <h1>Hello React!</h1>;

const myelement = <h1>Understanding JSX!</h1>;

ReactDOM.render(myelement, document.getElementById('root'));

const myelement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);

ReactDOM.render(myelement, document.getElementById('root'));

const myelement = (
<div> If we want to return more
<h1>I am a Header.</h1> elements, we need to wrap
<h1>I am a Header too.</h1> it with one container
</div> element. Notice how we
); are using div as a wrapper
for the two h1 elements.
ReactDOM.render(myelement, document.getElementById('root'));
Creating a functional component
• Components are the essential building blocks of any app created with React
 A single app most often consists of many components.
• A component is in essence, a piece of the UI - splitting the user interface into
reusable and independent parts, each of which can be processed separately.
 Components are independent and reusable bits of code.
 It’s an encapsulated piece of logic.
 They serve the same purpose as JavaScript functions, but work in isolation and return
HTML via a render function.

function ExpenseItem(){
return <h2>Expense Item</h2>
}
export default ExpenseItem;

const ExpenseItem = () => {


return <h2>Expense Item</h2>
}
export default ExpenseItem;

Creating a functional component


• Adding our component to main component
 To use this component in your application, use similar syntax as normal HTML

• Creating components makes them


reusable and configurable.
• Reusing is simple. Eg, simply copy
paste <ExpenseItem/> multiple times
in App.js.
Another example

import React, {Component} from 'react';


import './App.css'; return (
import Person from './Person/Person'; <div className="App">
function App() { <h1> Hi, welcome to React</h1>
return ( <Person />
<div className="App"> <Person />
<h1> Hi, welcome to React</h1> <Person />
<Person /> </div>
</div> );
);
}
export default App;

Making our functional component more complex


import "./ExpenseItem.css"

const ExpenseItem = () => {


return (
<div className="expense-item">
<div>Oct 20th 2021</div>
<div className="expense-item__description">
<h2>Paid Carpenter</h2>
<p className="expense-item__price">Rs 75000</p>
</div>
</div>
)
}
export default ExpenseItem;
Components & JSX
• When creating components, you have the choice between two different ways:
• Functional components (also referred to as "presentational", "dumb" or "stateless"
components)
using ES6 arrow functions as
const cmp = () => { shown here is recommended
return <div>some JSX</div> but optional
}

• class-based components (also referred to as "containers", "smart" or "stateful"


components)

class Cmp extends Component {


render () {
return <div>some JSX</div>
}
}

Outputting dynamic content


• If we have some dynamic content in our jsx part which we want to run as javaScript
code and not interpret as text, we have to wrap it in single curly braces.

import "./ExpenseItem.css"

const ExpenseItem = () => {

const expDate = new Date(2021, 7, 11);


const expTitle = "Paid carpenter";
const expAmount = 75000

return (
<div className="expense-item">

{/* single and multiline comments in JSX */}

<div>{expDate.toISOString()}</div>
<div className="expense-item__description"> Comments in JSX
<h2>{expTitle}</h2>
<p className="expense-item__price">Rs {expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;
Outputting dynamic content – another example
//Person.js Wrap dynamic
import React from 'react'; content in JSX in {...}

const person = () => {


return <p>Hi Person i am {Math.floor(Math.random() * 30)} years old</p>
}
export default person;

function App() {
return (
<div className="App">
<h1> Hi, welcome to React</h1>
<Person />
<Person />
<Person />
</div>
);
}
}

PROPS
Passing data via ‘Props’
• “Props” stands for properties.
 It is a special keyword in React used for passing data from one component to another.
 Props are arguments passed into React components.
 props are read-only. So, the data coming from a parent component can't be changed by
the child component.
 Props are passed to components via HTML attributes.
 Props can be used to pass any kind of data such as: String, Array, Integer, Boolean,
Objects or, Functions

import HelloComponent from "./HelloComponent";

const MessageComponent = () => {


return(
<div>
<HelloComponent name="Shrilata" />
</div>
);
} const HelloComponent = (props) => {
export default MessageComponent; return (<h3>Hello, welcome {props.name}</h3>)
}
export default HelloComponent;

Passing data via ‘Props’


function App() {
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpenseItem expDate="20-12-2020" expTitle="Myntra shopping" expAmount="2500"/>
<ExpenseItem expDate="21-12-2020" expTitle="Microwave" expAmount="8000"/>
</div>
);
}
export default App; you can use as many
props as you like

const ExpenseItem = (props) => {


return (
<div className="expense-item">
<div>{props.expDate}</div>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
</div>
) React uses ‘props’ to pass attributes from
} ‘parent’ component to ‘child’ component.
export default ExpenseItem;
Working with props
function App() {
return (
<div className="App">
<h1> Hi, welcome to React</h1>
<Person name="Shri" age="20"/>
<Person name="Soha" age="23”>Hobbies : Coding</Person>
<Person name="sandeep" age="45"/>
</div>
);

//Person.js
import React from 'react';

const person = (props) => {


return <p>Hi i am {props.name} and i am {props.age} years old</p>
}
export default person;
React uses ‘props’ to pass attributes from
‘parent’ component to ‘child’ component.

Working with props


function App() {
const expenses = [
{
title: 'Groceries',
amount: 900,
date: new Date(2020, 7, 14),
},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'SofaSet', amount: 25000, date: new Date(2021, 2, 28),
}
];

return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpenseItem expDate={expenses[0].date} expTitle={expenses[0].title}
expAmount={expenses[0].amount}/>
<ExpenseItem expDate={expenses[1].date} expTitle={expenses[1].title}
expAmount={expenses[1].amount}/>
<ExpenseItem expDate={expenses[2].date} expTitle={expenses[2].title}
expAmount={expenses[2].amount}/>
</div>
);
}
export default App;
“Javascript” in components
const ExpenseItem = (props) => {
const month = props.expDate.toLocaleString('en-US', {month: 'long'});
const day = props.expDate.toLocaleString('en-US', {day: '2-digit'});
const year = props.expDate.getFullYear();

return (
<div className="expense-item">
<div>
<div>{month}</div>
<div>{day}</div>
<div>{year}</div>
</div>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;

import ExpenseDate from "./ExpenseDate";


const ExpenseItem = (props) => { Splitting components further
return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
</div>
)
}
export default ExpenseItem;

import "./ExpenseDate.css"

const ExpenseDate = (props) => {


const month = props.date.toLocaleString('en-US', {month: 'long'});
const day = props.date.toLocaleString('en-US', {day: '2-digit'});
const year = props.date.getFullYear();
return (
<div className="expense-date">
<div className="expense-date__month">{month}</div>
<div className="expense-date__day">{day}</div>
<div className="expense-date__year">{year}</div>
</div>
);
}
export default ExpenseDate;
EVENTS AND EVENT HANDLING

Listening to events and working with event handlers


const ExpenseItem = (props) => {

let btnHandler = () => {


console.log("Button clicked!")
}

return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{props.expTitle}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;

No parenthesis ()
STATEFUL COMPONENTS

React State
• The state is a built-in React object that is used to contain data or information
about the component.
• A component’s state can change over time; whenever it changes, the
component re-renders.
 The change in state can happen as a response to user action or system-generated
events and these changes determine the behavior of the component and how it will
render.
• A component with state is known as stateful component.

• State allows us to create components that are dynamic and interactive.


 State is private, it must not be manipulated from the outside.
 Also, it is important to know when to use ‘state’, it is generally used with data that is
bound to change.
Component without state
const ExpenseItem = (props) => {

let title = props.expTitle;

let btnHandler = () => {


title = "updated expense"
console.log("Button clicked!")
}

return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{title}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;

React Hooks
• Hooks allow us to "hook" into React features such as state and lifecycle methods
 React Hooks are special functions provided by React to handle a specific functionality
inside a React functional component.
 Eg React provides useState() function to manage state in a functional component.
 When a React functional component uses React Hooks, React Hooks attach itself into
the component and provides additional functionality.

• You must import Hooks from react


 Eg : import React, { useState } from "react"; Here - useState is a Hook to keep track of
the application state.

• There are some rules for hooks:


 Hooks can only be called inside React function components.
 Hooks can only be called at the top level of a component.
 Hooks cannot be conditional
 Hooks will not work in React class components.
 If you have stateful logic that needs to be reused in several components, you can build
your own custom Hooks
Working with “state” in functional component
• The React useState Hook allows us to track state in a function component.
• To use the useState Hook, we first need to import it into our component.
 import { useState } from "react";
 We initialize our state by calling useState in our function component.

import React, {useState} from 'react';

const UseStateComponent = () => {


useState(); //hooks go here
}

 useState accepts an initial state and returns two values:


1. The current state.
2. A function that updates the state.
 Eg: function FavoriteColor() {
const [color, setColor] = useState("");
}

o The first value, color, is our current state.


o The second value, setColor, is the fuction that is used to update our state.
o Lastly, we set the initial state to an empty string: useState("")

Working with “state” in functional component


import React, {useState} from 'react';

const UseStateComponent = () => {


const [counter, setCounter] = useState(0); //hooks go here

const btnHandler = () => {


setCounter(counter+1);
console.log(counter, " button clicked")
}
return(
<div>
Counter : {counter} &nbsp;&nbsp;
<button onClick={btnHandler}>increment counter</button>
</div>
);
}
export default UseStateComponent;
Working with “state” in functional component
import React, {useState} from 'react'

const ExpenseItem = (props) => {

const [title, setTitle] = useState(props.expTitle);

let btnHandler = () => {


setTitle("updated expense")
console.log("Button clicked!")
}

return (
<div className="expense-item">
<ExpenseDate date={props.expDate}/>
<div className="expense-item__description">
<h2>{title}</h2>
<p className="expense-item__price">Rs {props.expAmount}</p>
</div>
<button onClick={btnHandler}>Change Title</button>
</div>
)
}
export default ExpenseItem;

props and state


• props and state are CORE concepts of React.
 Actually, only changes in props and/ or state trigger React to re-render your components
and potentially update the DOM in the browser
• Props : allow you to pass data from a parent (wrapping) component to a child
component.
 Eg : AllPosts Component : “title” is the custom property (prop) set up on the
custom Post component.
 Post Component: receives the props argument. React will pass one argument to your
component function; an object, which contains all properties you set up on <Post ... /> .
 {props.title} then dynamically outputs the title property of the props object - which is
available since we set the title property inside AllPosts component

//AllPosts //Post
const posts = () => { const post = (props) => {
return ( return (
<div> <div>
<Post title="My first Post" /> <h1>{props.title}</h1>
<Post title="My second Post" /> </div>
</div> );
); }
}
props and state
• State : While props allow you to pass data down the component tree (and hence
trigger an UI update), state is used to change the component’s, well, state from
within.
 Changes to state also trigger an UI update.
 Example: NewPost Component: this component contains state . Only class-based
components can define and use state . You can of course pass the state down to
functional components, but these then can't directly edit it.

class NewPost extends Component { // state can only be accessed in class-based components!
state = {
counter: 1
};

render () { // Needs to be implemented in class-based components! Return some JSX!


return (
<div>{this.state.counter}</div>
);
}
}

props and state


• Props are immutable.
• They should not be updated by the component to which they are passed.
• They are owned by the component which passes them to some other
component.

• State is something internal and private to the component.


• State can and will change depending on the interactions with the outer world.
• State should store as simple data as possible, such as whether an input
checkbox is checked or not or a CSS class that hides or displays the
component
Simple example : props + state
import React, {useState} from 'react'
import ChildComponent from './ChildComponent';

const ParentComponent = () => {


const [uname, setUname] = useState('Shrilata')
const [email, setEmail] = useState('[email protected]')

return(
<ChildComponent uname={uname} email={email} />
);
} function App() {
export default ParentComponent; return (
<div className="App">
<h2>Welcome to React!</h2>
const ChildComponent = (props) => { <ParentComponent />
return( ...
<div>
<div>Name : {props.uname}</div>
<div>Email : {props.email}</div>
</div>
);
}
export default ChildComponent;

USING FORM FOR INPUT


const NewExpense = () => {
return(
Adding form inputs <div className="new-expense">
<ExpenseForm />
import "./ExpenseForm.css" </div>
const ExpenseForm = () => { );
return( }
<form> export default NewExpense;
<div className="new-expense__controls">
<div className="new-expense__control">
<label>Title</label>
<input />
</div>
<div className="new-expense__control">
<label>Amount</label>
<input type="number"/>
</div>
<div className="new-expense__control">
<label>Date</label>
<input type="date" min="2019-01-01"
max="2022-12-31" />
</div>
</div>
<div className="new-expense__actions">
<button type="submit">Add Expense</button>
</div>
</form>
);
}
export default ExpenseForm;

Listening to user input


const ExpenseForm = () => {

const titleChangeHandler = (event) => {


console.log(event.target.value)
}
return(
<form>
<div className="new-expense__controls">
<div className="new-expense__control">
<label>Title</label>
<input onChange={titleChangeHandler}/>
</div>
...
</div>
<div className="new-expense__actions">
<button type="submit">Add Expense</button>
</div>
</form>
);
}
export default ExpenseForm;
Storing input into state – working with multiple states
import React, {useState} from 'react';
const ExpenseForm = () => {

const [inputTitle, setInputTitle] = useState('')


const [inputAmount, setInputAmount] = useState('')
const [inputDate, setInputDate] = useState('')

const titleChangeHandler = (event) => {


setInputTitle(event.target.value)
}
const amountChangeHandler = (event) => {
setInputAmount(event.target.value)
}
const dateChangeHandler = (event) => {
setInputDate(event.target.value)
}
return(
<form>
<div className="new-expense__controls">
<div className="new-expense__control">
<label>Title</label> <input onChange={titleChangeHandler}/>
</div>
<div className="new-expense__control">
<label>Amount</label>
<input type="number" onChange={amountChangeHandler}/>
</div> ...

Form submission
Form submission – extracting data, 2-way binding
const ExpenseForm = () => {

const [inputTitle, setInputTitle] = useState('')


const [inputAmount, setInputAmount] = useState('')
const [inputDate, setInputDate] = useState('')

const titleChangeHandler = (event) => {...}


const amountChangeHandler = (event) => {...}
const dateChangeHandler = (event) => {...}

const submitHandler = (event) => {


event.preventDefault();
const expenseData = {
title:inputTitle,
amount:inputAmount, return(
date:inputDate <form onSubmit={submitHandler}>
} <div className="new-expense__controls">
console.log(expenseData) <div className="new-expense__control">
setInputAmount('') <label>Title</label>
setInputDate('') <input value={inputTitle}
setInputTitle('') onChange={titleChangeHandler}/>
} </div>
...
</form>
);
}

Passing data from child to parent component


const NewExpense = () => {

const saveExpenseDataHandler = (inputExpenseData) => {


const expenseData = {
...inputExpenseData,
id:Math.random().toString()
}
console.log("In NewExpense ",expenseData)
}
return(
<div className="new-expense">
<ExpenseForm onSaveExpenseData={saveExpenseDataHandler}/>
</div>
); const ExpenseForm = (props) => {
}
...
export default NewExpense; const submitHandler = (event) => {
event.preventDefault();
const expenseData = {
title:inputTitle,
amount:inputAmount,
date: new Date(inputDate)
}
//console.log(expenseData)
props.onSaveExpenseData(expenseData);
...
}
Passing data from child to parent
function App() {
const expenses = [...];

const addExpenseHandler = expense => {


console.log("In App component ", expense)
}

return (
<div className="App">
<h2>Welcome to React!</h2>
<NewExpense onAddExpense={addExpenseHandler} />
...
); const NewExpense = (props) => {
}
export default App; const saveExpenseDataHandler = (inputExpenseData) => {
const expenseData = {
...inputExpenseData,
id:Math.random().toString()
}
//console.log("In NewExpense ",expenseData)
props.onAddExpense(expenseData)
}
return(...);
}
export default NewExpense;

LIFTING STATE UP
Lifting state up in React.js
• In a typical application, you pass a lot of state down to child components as props.
 These props are often passed down multiple component levels.
 That's how state is shared vertically in your application.
• Often there will be a need to share state between different components.
 The common approach to share state between two components is to move the state to
common parent of the two components.
 This approach is called as lifting state up in React.js
 React components can manage their own state
 Often components need to communicate state to others
 Siblings do not pass state to each other directly
 State should pass through a parent, then trickle down

App

C1 C2

C11 C12 C21

Lifting state up – simple example


import React, {useState} from 'react'
import Display from './Display'
import Button from './Button'

const ClickCounter = () => {


const [counter, setCounter] = useState(0)

const incrCounter = () => { const Display = (props) => {


setCounter(counter + 1) return <p>{props.message}</p>;
} }
return( export default Display;
<div>
<Button onClick={incrCounter}>Button</Button>
<Display message={`Clicked ${counter} times`}/>
</div>
);
}
export default ClickCounter;

const Button = (props) => {


return <button onClick={props.onClick}>Click me</button>;
}
export default Button;
A small aside – add filter to date
const ExpensesFilter = (props) => {

const selectChangeHandler = (event) => {


console.log(event.target.value)
props.onSelectYear(event.target.value)
}
return (
<div className='expenses-filter'> App

<div className='expenses-filter__control'>
<label>Filter by year</label>
<select onChange={selectChangeHandler}> ExpenseItem NewExpense ExpensesFilter

<option value='2022'>2022</option>
<option value='2021'>2021</option>
<option value='2020'>2020</option> ExpenseDate ExpenseForm
<option value='2019'>2019</option>
</select>
</div> function App() {
</div> const [filteredYear, setFilteredYear] = useState(2020);
);
}; const selectYearHandler = filteredValue => {
export default ExpensesFilter; setFilteredYear(filteredValue)
}
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpensesFilter onSelectYear={selectYearHandler}/>

WORKING WITH LISTS AND


CONDITIONALS
const SimpleListComponent = () => {
const nums = [1,2,3,4,5] Working with lists
const updatedNums = nums.map((num)=>{
return <li>{num*num}</li>;
});

const items =[{name:'Item-1'}, {name:'Item-2'}]


const updatedItems = items.map(item => (
<p>{item.name}</p>
))

const students = [{name:"Anita",rollno:101},


{name:"Sunita",rollno:102},
{name:"Kavita",rollno:103}]
const updatedStudents = students.map(student => (
<tr>
<td>Name {student.name} </td>
<td>Rollno {student.rollno} </td>
</tr>
))
return(
<div>
<h2> Numbers List</h2> {updatedNums}
<h2> Items List</h2> {updatedItems}
<h2> Students List</h2>
<table border="1">{updatedStudents}</table>
</div>
);}
export default SimpleListComponent

Working with lists in child component


import SimpleListChildComponent from "./SimpleListChildComponent";

const SimpleListComponent = () => {


const nums = [1,2,3,4,5]

const items =[{name:'Item-1'}, {name:'Item-2'}]

const students = [{name:"Anita",rollno:101},


{name:"Sunita",rollno:102},
{name:"Kavita",rollno:103}]
return(
<div> const SimpleListChildComponent = (props) => {
<SimpleListChildComponent
nums={nums} const nums = props.nums;
items={items} const updatedNums = nums.map(...);
students={students} /> const items = props.items
</div> const updatedItems = items.map(...)
);
} const students = props.students;
export default SimpleListComponent const updatedStudents = students.map(...)

return(...);
}
export default SimpleListChildComponent;
Working with the expenses list
const expenses = [
{ title: 'Groceries’, amount: 900, date: new Date(2020, 7, 14)},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'SofaSet', amount: 25000, date: new Date(2021, 2, 28)}
];
return (
<div className="App">
<h2>Welcome to React!</h2>
<ExpenseItem
expDate={expenses[0].date}
expTitle={expenses[0].title}
expAmount={expenses[0].amount}
/>
<ExpenseItem
expDate={expenses[1].date}
expTitle={expenses[1].title}
expAmount={expenses[1].amount}
/>
<ExpenseItem
expDate={expenses[2].date}
expTitle={expenses[2].title}
expAmount={expenses[2].amount}
/>
</div>
);
}

Working with the expenses list


function App() {
const expenses = [
{ title: 'Groceries', amount: 900, date: new Date(2020, 7, 14)},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'Sofa Set', amount: 25000, date: new Date(2021, 2, 28)}
];
return (
<div className="App"> {expenses.map(expense =>
<h2>Welcome to React!</h2> (<ExpenseItem
expDate={expense.date}
{expenses.map(expense => { expTitle={expense.title}
return <ExpenseItem expAmount={expense.amount}
expDate={expense.date} />))
expTitle={expense.title} }
expAmount={expense.amount}
/>
})}
{/* <ExpenseItem
expDate={expenses[0].date}
expTitle={expenses[0].title}
expAmount={expenses[0].amount}
/> ... */}
</div>
);
}
export default App;
const DUMMY_EXP = [
Using stateful lists
{ title: 'Groceries', amount: 900, date: new Date(2020, 7, 14)},
{ title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ title: 'New Sofa Set', amount: 25000, date: new Date(2021, 2, 28)}
];
function App() {
const [expenses, setExpenses] = useState(DUMMY_EXP)

const addExpenseHandler = expense => {


setExpenses(prevArr => {return [expense, ...prevArr]})
}
return (
<div className="App">
<h2>Welcome to React!</h2>
<NewExpense onAddExpense={addExpenseHandler} />

{expenses.map(expense => (<ExpenseItem


expDate={expense.date}
expTitle={expense.title}
expAmount={expense.amount}
/>))
}
</div>
);
}
export default App;

Lists and keys

const DUMMY_EXP = [
{ id:101, title: 'Groceries', amount: 900, date: new Date(2020, 7, 14)},
{ id:102,title: 'New TV', amount: 34000, date: new Date(2021, 2, 12) },
{ id:103,title: 'New Sofa Set', amount: 25000, date: new Date(2021, 2, 28)}
];

function App() {

const [expenses, setExpenses] = useState(DUMMY_EXP)


...
return (
<div className="App">
...
{expenses.map(expense => (
<ExpenseItem
key={expense.id}
expDate={expense.date}
expTitle={expense.title}
expAmount={expense.amount}
/>))
}
...
Lists and keys
• When creating a list in JSX, React may show you an error and ask for a key.
 Keys are unique identifiers that must be attached to the top-level element inside a map.
 Keys are used by React to know how to update a list whether adding, updating, or deleting
items.
 This is part of how React is so fast with large lists.
 Keys are a way to help React know how to efficiently update a list.
 We can add a key using the key prop like so:

<div>
{people.map(person => (
<p key={person.name}>{person.name}</p>
))}
</div>

Implementing filters
function App() {
const [expenses, setExpenses] = useState(DUMMY_EXP)
const [filteredYear, setFilteredYear] = useState(2020);

const filteredExpensesArr = expenses.filter(expense =>{


return expense.date.getFullYear().toString() === filteredYear;
})

...
const selectYearHandler = filteredValue => {
setFilteredYear(filteredValue)
}

return (
<div className="App">
<h2>Welcome to React!</h2>
<NewExpense onAddExpense={addExpenseHandler} />
<ExpensesFilter onSelectYear={selectYearHandler}/>
{filteredExpensesArr.map(expense => (
<ExpenseItem
key={expense.id}
expDate={expense.date}
expTitle={expense.title}
expAmount={expense.amount}
/>))
}
Rendering content conditionally
• Conditional rendering means to render a specific HTML element or React
component depending on a prop or state value.
 In a conditional render, a React component decides based on one or several conditions
which DOM elements it will return.
 For instance, based on some logic it can either return a list of items or a text that says
"Sorry, the list is empty".

if(condition_is_met) {
renderSectionOfUI();
}

Rendering content conditionally : example


/*const users = [
{ id: '1', firstName: 'Shrilata', lastName: 'T' },
{ id: '2', firstName: 'Anita', lastName: 'Patil' },
];*/
const users = []
if (!list.length) {
function ListUsers() { return <p>Sorry, the list is empty.</p>;
return ( }
<div>
<List list={users} />
</div> function Item({ item }) {
); return (
} <li>
{item.firstName} {item.lastName}
function List({ list }) { </li>
if (!list) { );
return null; }
} export default ListUsers;
return (
<ul>
{list.map(item => (
<Item key={item.id} item={item} />
))}
</ul>
);
}
Rendering content conditionally : Expense tracker example

{filteredExpensesArr.length ==0 ? <p>No expenses found</p> :


filteredExpensesArr.map(expense => (
<ExpenseItem
key={expense.id}
expDate={expense.date}
expTitle={expense.title}
expAmount={expense.amount}
/>))
}

Rendering content conditionally : one more example


const NewExpense = (props) => {
const [showForm, setShowForm] = useState(false)

const showFormHandler = () => {


setShowForm(true)
}
const saveExpenseDataHandler = (inputExpenseData) => {...}
return(
<div className="new-expense">
{!showForm && <button onClick={showFormHandler}>Add New Expense </button>}
{showForm && <ExpenseForm onCancel={stopShowForm}
onSaveExpenseData={saveExpenseDataHandler}/>}
</div>
);
}
export default NewExpense;

//ExpenseForm
<div className="new-expense__actions">
<button type="button"
onClick={props.onCancel}>Cancel</button>
<button type="submit">Add Expense</button>
</div>
CLASS-BASED COMPONENTS
const HelloComponent = (props) => {
Functional components are regular
return (<h3>Hello, welcome user!!</h3>)
javascript functions which return
}
renderable results (typically JSX)
export default HelloComponent;

class HelloComponent extends Component{


render(){ Class based components are
return (<h3>Hello, welcome user!!</h3>) defined using Javascript classes
} where a render method defines the
} to-be-rendered output
export default HelloComponent;

Class-based components : Examples


import React, {Component} from 'react';
class HelloComponent extends Component{
render(){
return (<h2>Hello class-based component</h2>)
}
}
export default HelloComponent;

import './User.css';
import React, {Component} from 'react';

class User extends Component{


render(){
return <li className='user'>Hello User</li>
}
}; function App() {
export default User; return (
<div className="App">
<h1> Welcome to React</h1>
<HelloComponent />
<User />
</div>
);
}
Class-based components : passing into props
import React, {Component} from 'react'; function App() {
import User from './User' return (
<div className="App">
const DUMMY_USERS = [ <h1> Welcome to React</h1>
{ id: 'u1', name: 'Shrilata' }, <Users />
{ id: 'u2', name: 'Soha' }, </div>
{ id: 'u3', name: 'Sia' }, );
]; }

class Users extends Component{


render(){
return(
<div>
<User name={DUMMY_USERS[0].name} />
<User name={DUMMY_USERS[1].name} />
<User name={DUMMY_USERS[2].name} />
</div>
); import './User.css';
} import React, {Component} from 'react';
}
export default Users; class User extends Component{
render(){
return (<li className='user'>Hello {this.props.name}</li>);
}
};
export default User;

React State : Example


import React, {Component} from 'react';
import './App.css';
import StatefulComponent from "./StatefulComponent/StatefulComponent";

class App extends Component {


render() { import React,{Component} from 'react';
return (
<div> class statefulComponent extends Component{
<StatefulComponent /> state = {
</div> name: "Shrilata",
); email: "[email protected]",
} address:"Pune"
} }
export default App; render(){
return(
<div>
<h3>Name : {this.state.name}</h3>
<h3>Email : {this.state.email}</h3>
<h3>Address : {this.state.address}</h3>
</div>
);
}
}
export default statefulComponent;
State and props
const person = (props) => {
return (
<div>
<p>Hi i am {props.name}
class App extends Component { and i am {props.age} years old</p>
state = { </div>
persons:[ )
{name:"Shri",age:20}, }
{name:"Soha",age:23}, export default person;
{name:"Sandeep",age:30},
]
}
render() {
return (
<div className="App">
<h1> Hi, welcome to React</h1>
<button>Switch name</button>
<Person name={this.state.persons[0].name} age={this.state.persons[0].age}/>
<Person name={this.state.persons[1].name} age={this.state.persons[1].age}>
Hobbies : Coding
</Person>
<Person name={this.state.persons[2].name} age={this.state.persons[2].age}/>
</div>
);
}
}

LIFECYCLE EVENTS
Lifecycle Events
• React class components can have hooks for several lifecycle events
 During the lifetime of a component, there’s a series of events that gets called, and to
each event you can hook and provide custom functionality.
 React lifecycle methods are a series of events that happen from the birth of a React
component to its death.
 There are 4 phases in a React component lifecycle:
o initial
o Mounting
o Updating
o Unmounting

class HelloComponent extends Component{


constructor(){
super();
this.state = {message: “hello” }
}
render(){
return (<h2>Hello World</h2>)
}
}

Lifecycle methods
• React lifecycle methods:
 Each React lifecycle phase has a number of lifecycle methods that you can override
to run code at specified times during the process.
 These are popularly known as component lifecycle methods.

• Initialisation phase:
 Constructor(props): This is a special function that is called when new components
are created. In this, we initialize the state or props of the component.
Lifecycle methods
• The mounting phase refers to the phase during which a component is created and
inserted to the DOM.
• The following methods are called in order.
 ComponentWillMount(): This function is called immediately before mounting occurs. It
is called right before the first rendering is performed.
 render(): You have this method for all the components created. It returns the Html node.

 componentDidMount(): This method is called right after the


react component is mounted on DOM or you can say that it
is called right after render method executed for the first time
 Here we can make API call, foreg, interact with dom or
perform any ajax call to load data.

class HelloComponent extends Component{


componentDidMount(){
console.log("Mounted component")
}
render(){
return <h1>Hello</h1>
}
}

Lifecycle methods
• Update: In this state, the dom is interacted by a user and
updated. For example, you enter something in the textbox,
so the state properties are updated.
 The component is re-rendered whenever a change is made to
react component’s state or props, you can simply say that the
component is updated.
• Following are the methods available in update state:
 shouldComponentUpdate() : called when the component is
updated.
 componentDidUpdate() : after the component is updated.

• UnMounting: this state comes into the picture when the Component is not required
or removed.
• Following are the methods available in unmount state:
 ComponentWillUnmount(): called when the Component is removed or destroyed.
import React, {Component} from 'react';

class LifecycleComponent extends Component {


constructor(props) {
super(props);
this.state = {name: ''};

this.UpdateName = this.UpdateName.bind(this);
this.testclick = this.testclick.bind(this);
}

UpdateName(event) {
this.setState({name: event.target.value});
}

testclick(event) {
alert("The name entered is: "+ this.state.name);
}

componentDidMount() {
console.log('Mounting State : calling method componentDidMount');
}

shouldComponentUpdate() {
console.log('Update State : calling method shouldComponentUpdate');
return true;
}

componentDidUpdate() {
console.log('Update State : calling method
componentDidUpdate')
}
componentWillUnmount() {
console.log('UnMounting State : calling method
componentWillUnmount');
}

render() {
return (
<div>
Enter Your Name:<input type="text"
value={this.state.name} onChange={this.UpdateName} /><br/>
<h2>{this.state.name}</h2>
<input type="button"
value="Click Here"
onClick={this.testclick} />
</div>
);
}
}

export default LifecycleComponent;

Lifecycle Methods (kirupa.com)


ERROR BOUNDARIES

Using Error Boundaries


const person = (props) => {
const rnd = Math.random();
if(rnd > 0.7){
throw new Error("Something went wrong");
}
return (
...
)
};
export default person;

class Users extends Component{

componentDidUpdate(){
if(this.props.users.length == 0)
throw new Error("No users in list!")
}
...

• A JavaScript error in a part of the UI shouldn’t break the whole app.


• To solve this problem for React users, React 16 introduces a new concept of
an “error boundary”.
Using Error Boundaries
import React, {Component} from 'react';
class ErrorBoundary extends Component{
state = {
hasError:false,
errorMessage:''
}
componentDidCatch = (error, info) => {
Use it like this:
this.setState({hasError:true, errorMessage:error});
<ErrorBoundary>
}
<Artists />
render(){
</ErrorBoundary>
if(this.state.hasError)
return <h1>{this.state.errorMessage}</h1>
else
return this.props.children
}
}
export default ErrorBoundary;

• Error boundaries are React components that catch JavaScript errors anywhere in their child
component tree, log those errors, and display a fallback UI instead of the component tree that
crashed. Error boundaries catch errors during rendering
• https://reactjs.org/docs/error-boundaries.html
• React.Component – React (reactjs.org)

Using Error Boundaries


function App() {
return (
<div className="App">
<h1> Welcome to React</h1>
<ErrorBoundary >
<Person />
</ErrorBoundary>
</div>
);
}
FORMS AND FORMS VALIDATION
Handling user input the right way

Controlled Components and Uncontrolled components


• React forms present a unique challenge because you can either allow the
browser to handle most of the form elements and collect data through React
change events, or you can use React to fully control the element by setting
and updating the input value directly.
 The first approach is called an uncontrolled component because React is not setting
the value.
 The second approach is called a controlled component because React is actively
updating the input.

• In HTML, form data is usually handled by the DOM.


• In React, form data is usually handled by the components.
 When the data is handled by the components, all the data is stored in the
component state.
Controlled Inputs in class components
• An input is said to be “controlled” when React is responsible for maintaining and
setting its state.
 The state is kept in sync with the input’s value, meaning that changing the input will
update the state, and updating the state will change the input.

class ControlledInput extends React.Component {


state = { name: '' };

handleInput = (event) => {


this.setState({name: event.target.value });
}
handleSubmit = (event) => {
alert('A name was submitted: ' + this.state.name);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
Name : <input value={this.state.name}
onChange={this.handleInput} />
<input type="submit" value="Submit" />
</form>
);
}
}

Controlled Inputs using React hooks (functional components)


import React, {useState} from 'react'

const SimpleInput = (props) => {


const [inputName, setInputName] = useState('')

const inputNameHandler = (event) => {


setInputName(event.target.value)
}

const formSubmitHandler = event => {


event.preventDefault();
console.log(inputName)
}
return (
<form onSubmit={formSubmitHandler}>
<div className='form-control'>
<label htmlFor='name'>Your Name</label>
<input type='text' id='name' onChange={inputNameHandler}/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;
Controlled Inputs
• Controlled inputs open up the following possibilities:
• instant input validation: we can give the user instant feedback without having to
wait for them to submit the form (e.g. if their password is not complex enough)
• instant input formatting: we can add proper separators to currency inputs, or
grouping to phone numbers on the fly
• conditionally disable form submission: we can enable the submit button after
certain criteria are met (e.g. the user consented to the terms and conditions)
• dynamically generate new inputs: we can add additional inputs to a form based
on the user’s previous input (e.g. adding details of additional people on a hotel
booking)

Handling Multiple Form Inputs


class ControlledLoginForm extends React.Component {
state = {
username: '', • {username: ‘shrilata’} //where username is
email: '' event.target.name which is field name ie
}; username
handleInput = (event) => { • {email: ‘[email protected]’} //where email is
let name = event.target.name; event.target.name which is field name ie email
let val = event.target.value;
this.setState({[name]: val});
console.log(this.state)
}
handleSubmit = (event) => {
alert('A name was submitted: ’
+ this.state.username);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<h3>Hello {this.state.username} {this.state.email}</h3>
Name : <input name="username" onChange={this.handleInput} /><br />
Email : <input name="email" onChange={this.handleInput} />
<input type="submit" value="Submit" />
</form>
); }
}
One more
example

class MultipleInputFields extends Component {

state = {
name:'',
onservation:'',
color:'',
size:'',
}
handleChanges = (event) => {
let name = event.target.name;
let val = event.target.value;
this.setState({[name]: val});
console.log(this.state)
};
submitFormHandler = (event) => {
event.preventDefault();
console.log("from submit ", this.state);
};
render(){
const colors = ['Blue', 'Red', 'Green', 'Yellow'];
const sizes = ['Small', 'Medium', 'Large', 'XL', 'XXL', '3XL'];

return (
<form onSubmit={this.submitFormHandler}>
<div className='form-control'>
<label>Name:</label>
<input name="name" type="text" value={this.state.name} onChange={this.handleChanges} />
</div>
<div className='form-control'>
<label>Observation:</label>
<textarea name="observation" value={this.state.observation} onChange={this.handleChanges} />
</div>
<div className='form-control'>
<label>Desired color:</label>
<select name="color" value={this.state.color} onChange={this.handleChanges}>
{colors.map((color, i) => <option key={i} value={color.toLowerCase()}>{color}</option>)}
</select>
</div>
<div >
<label>T-shirt Size:</label>
{sizes.map((size, i) =>
<label key={i}> {size}
<input
name="size" value={size.toUpperCase()} checked={this.state.size === size.toUpperCase()}
onChange={this.handleChanges} type="radio" />
</label>
)}
</div>
<div className="form-actions">
<button type="submit">Submit</button>
</div>
</form>
)}
}
export default MultipleInputFields;
Controlled components : Summary
• A controlled component is bound to a value, and its adjustments will be
handled in code by using event-based callbacks.
 Here, the input form variable is handled by the react itself rather than the DOM.
 In this case, the mutable state is maintained in the state property and modified using
setState().
• Controlled components have functions which regulate the data that occurs at
each on Change event.
 This data is subsequently saved in the setState() method and updated. It helps
components manage the elements and data of the form easier.

• You can use the controlled component when you create:
 Forms validation so that when you type, you always have to know the input value to
verify whether it is true or not!
 Disable submission icon, except for valid data in all fields
 If you have a format such as the input for a credit card

Validation
class ControlledInputValidation1 extends React.Component {
state = { age: '' };

handleInput = (event) => {


let nam = event.target.name;
let val = event.target.value;
if (nam === "age") {
if (!Number(val))
alert("Age must be a number");
}
this.setState({[nam]: val});
}
handleSubmit = (event) => {
alert('A age was submitted: ' + this.state.age);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
Age : <input name="age" value={this.state.age} onChange={this.handleInput}
/>
<input type="submit" value="Submit" />
</form>
);
}
}
Uncontrolled Inputs
• “uncontrolled” form inputs: React doesn’t track the input’s state.
 HTML input elements naturally keep track of their own state as part of the DOM, and
so when the form is submitted we have to read the values from the DOM elements
themselves.

• “uncontrolled” form inputs: React doesn’t track the input’s state.


 If the DOM handles the data, then the form is uncontrolled, and if the state of the
form component manages the data, then the form is said to be controlled

 Uncontrolled components are inputs that do not have a value property. In opposite
to controlled components, it is the application's responsibility to keep the component
state and the input value in sync.

 In order to do this, React allows us to create a “ref” (reference) to associate with an


element, giving access to the underlying DOM node

Uncontrolled Inputs
• In uncontrolled components form
data is being handled by DOM itself.
• For example here we can reference
form values by name
• This is quick and dirty way of handling
forms. It is mostly useful for simple
forms or when you are just learning
React.

• HTML input elements keep track of


their own state
 When the form is submitted we
typically read the values from the
DOM elements ourselves
Uncontrolled Inputs
• “ref is used to receive the form value from DOM.
 To enable this, React allows us to create a “ref” (reference) to associate with an element,
giving access to the underlying DOM node.
 Refs provide a way to access DOM nodes or React elements created in the render
method.
 Refs are created using React.createRef() and attached to React elements via the ref
attribute.
 Refs are commonly assigned to an instance property when a component is constructed so
they can be referenced throughout the component.

class MyComponent extends React.Component {


constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}

Uncontrolled Inputs
import React, {Component} from 'react'; • You initialize a new ref in the
class SimpleForm extends Component { constructor by calling
constructor(props) { React.createRef, assigning it to
super(props); an instance property so it’s
// create a ref to store the DOM element available for the lifetime of the
this.nameEl = React.createRef(); component.
} • In order to associate the ref with
an input, it’s passed to the
handleSubmit = (e) => { element as the
e.preventDefault(); special ref attribute.
alert(this.nameEl.current.value); • Once this is done, the input’s
} underlying DOM node can be
accessed via
render() { this.nameEl.current.
return (
<form onSubmit={this.handleSubmit}>
<label>Name:
<input type="text" ref={this.nameEl} />
</label>
<input type="submit" name="Submit" />
</form>
)
}
}
export default SimpleForm;
class LoginForm extends Component {
constructor(props) {
super(props);
Another example : Login form
this.nameEl = React.createRef();
this.passwordEl = React.createRef();
this.rememberMeEl = React.createRef();
}
handleSubmit = (e) => {
e.preventDefault();
const data = {
username: this.nameEl.current.value,
password: this.passwordEl.current.value,
rememberMe: this.rememberMeEl.current.checked,
}
console.log(data)
}
render(){
return (
<form onSubmit={this.handleSubmit}>
<fieldset><legend>Login Form</legend>
<input type="text" placeholder="username" ref={this.nameEl} /><br></br>
<input type="password" placeholder="password" ref={this.passwordEl} /><br></br>
<label><input type="checkbox" ref={this.rememberMeEl} />Remember me
</label><br></br>
<button type="submit" className="myButton">Login</button>
</fieldset>
</form>
);
}}

COMPOSITION VS. INHERITANCE


Composition over Inheritance
• Composition and inheritance are the approaches to use multiple components
together in React.js .
• This helps in code reuse.
• React recommend using composition instead of inheritance as much as
possible and inheritance should be used in very specific cases only.
• Composition works with functions as well as classes both.

class Automobile { Inheritance in JS


constructor() {
this.vehicleName = automobile;
this.numWheels = null;
}
printNumWheels() {
console.log(`This ${this.vehicleName} has ${this.numWheels} wheels`);
}
}
class Car extends Automobile {
constructor() {
super(this);
this.vehicleName = 'car';
this.numWheels = 4;
}
}
class Bicycle extends Automobile {
constructor() {
super(this);
this.vehicleName = 'bike';
this.numWheels = 2;
}
}
const car = new Car();
const bike = new Bicycle();
car.printNumWheels() // This car has 4 wheels
bike.printNumWheels() // This bike has 2 wheels
class Parent extends React.Component {
constructor(props) {
super(props);
this.methodA = this.methodA.bind(this);
}

methodA() {
console.log("methodA in parent class"); Console output
}

render() {
return false;
}
}

import Parent from "./parent";

class Child extends Parent {


constructor() {
super();
}
render() {
console.log("In child class, calling parent method...");
this.methodA();
return false;
}
}

Composition
• Composition is a code reuse technique where a larger object is created by
combining multiple smaller objects.

class App extends React.Component {


render() {
return <Toolbar theme="dark" />;
}
}

function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}

class ThemedButton extends React.Component {


render() {
return <Button theme={this.props.theme} />;
}
}
class App extends Component {
state = {
date:new Date()
...
}
...
return (
<div className="container">
<NewsHeader className="news" subject="Sports"
date={this.state.date.toString()} />

const newsHeader = (props) => {


return(
<div>
<h1>News for {props.date}</h1>
<h2>News Heading : {props.subject}</h2>
<NewsContent title="Content Title-1" content="Lots of Content-1" />
<NewsContent title="Content Title-2" content="Lots of Content-2" />
<NewsContent title="Content Title-3" content="Lots of Content-3" />

const author = (props) => {


const newsContent = (props) => { return(
return( <h6>Author for {props.title} - {props.name}</h6>
<div>
{/*complex code that filters out news based on subject*/}
<h4><b><i>News Title {props.title}</i></b></h4>
<h4>News Content : {props.content}</h4>
<Author title={props.title} name="Shrilata" />

CONTEXT
Context
• Context is designed to share data that can be considered “global” for a tree of React
components, such as the current authenticated user, theme, or preferred language

class App extends React.Component {


render() {
return <Toolbar theme="dark" />;
}
}

function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}

class ThemedButton extends React.Component {


render() {
return <Button theme={this.props.theme} />;
}
}

React Context API


• Store the state in a Context value in the common ancestor component (called
the Provider Component), and access it from as many components as
needed (called Consumer Components), which can be nested at any depth
under this ancestor.
• This solution has the same benefits as the Props solution, but because of
what could be called “hierarchical scoping”, it has the added benefit that any
component can access the state in any Context that is rooted above itself in
React’s hierarchy, without this state needing to be passed down to it as
props.
• React.js takes care of all the magic behind the scenes to make this work.

• Primary situations where the React Context


API really shines are:
 When your state needs to be accessed or set
from deeply nested components.
 When your state needs to be accessed or set
from many child components.
Three aspects to using React Contexts
• 1) Defining the Context object so we can use it.
 If we wanted to store data about the current user of a web app, we could create a
UserContext that can be used in the next two steps:
// Here we provide the initial value of the context Note: It doesn’t matter where this
const UserContext = React.createContext({ Context lives, as long as it can be
currentUser: null, accessed by all components that need
}); to use it in the next two steps.

• 2) Providing a value for a Context in the hierarchy.


 Assuming you had an AccountView component, you might provide a value like this

const AccountView = (props) => {


const [currentUser, setCurrentUser] = React.useState(null);
return (
{/* Here we provides the actual value for its descendents */}
<UserContext.Provider value={{ currentUser: currentUser }}>
<AccountSummary/>
<AccountProfile/>
</UserContext.Provider>
);
};

Three aspects to using React Contexts


• 3) Accessing the current Context value lower in the hierarchy.
 If the AccountSummary component needed the user, we could have just passed it as a
prop. But let’s assume that it doesn’t directly access the user data, but rather contains
another component that does:

// Here we don't use the Context directly, but render children that do.
const AccountSummary = (props) => {
return (
<AccountSummaryHeader/>
<AccountSummaryDashboard/>
<AccountSummaryFooter/>
);
};

 All three of these child components may not want to access the current user’s data. But as
an example, let’s just look at the AccountSummaryHeader component:
const AccountSummaryHeader = (props) => {
// Here we retrieve the current value of the context
const context = React.useContext(UserContext);
return (
<section><h2>{context.currentUser.name}</h2> </section>
);
};
Context
• Using context, we can avoid passing props through intermediate elements
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
return (
<ThemeContext.Provider value="dark">
<Toolbar />
</ThemeContext.Provider>
);
}
}
// A component in the middle doesn't have to pass the theme down explicitly anymore
function Toolbar() {
return (
<div>
<ThemedButton />
</div>
);
}
class ThemedButton extends React.Component {
static contextType = ThemeContext;
render() {
return <Button theme={this.context} />;
}
}

Bringing Bootstrap into your React App


• After creating your app project:
• ..Demo\second-app>npm install --save react-bootstrap bootstrap@3
• Then start the app : npm start

• In Index.js, put these as the 1st 2 lines:


• import 'bootstrap/dist/css/bootstrap.css';
• import 'bootstrap/dist/css/bootstrap-theme.css’;

• Now use Bootstrap classes in App.js or any other component:


• Eg :

render(){
return(
<div className=“container”>
<h1 className="text-danger">TODO LIST </h1>
REDUX
Because state management can be hard

What is state
• Eg: const state = { <div className={this.state.signUpModal.open ? 'hidden' : ''}>
posts: [], Sign Up Modal
signUpModal: { </div>
open: false
}
}

• state references the condition of something at a particular point in time, such as


whether a modal is open or not.
• In a React component the state holds data which can be rendered to the user.
• The state in React could also change in response to actions and events: in fact you
can update the local component’s state with this.setState().
• So, in general a typical JavaScript application is full of state. For example, state is:
 what the user sees (data)
 the data we fetch from an API
 the URL
 the items selected inside a page
 eventual errors to show to the user
State can be complex
• Even an innocent single page app could grow out of control without clear
boundaries between every layer of the application. This holds particularly true
in React.
 You can get by with keeping the state within a parent React component (or in
context) as long as the application remains small.
 Then things will become tricky especially when you add more behaviours to the app.
At some point you may want to reach for a consistent way to keep track of state
changes.

Create a Redux application


npx create-react-app redux-app
cd redux-app
npm install redux react-redux

import React from 'react';


import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

//STORE -> GLOBALISED STATE

//ACTION -> INCREMENT

//REDUCER

//DISPATCH

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
Create a Redux application
import {createStore} from 'redux’;
• Step-1 : Create the store: const myStore = createStore(reducer-name)

• Step-2 : Create action const increment = () => {


return {
type :'INCREMENT' //name of the action
}
}
const decrement = () => {
return {
type :'DECREMENT' //name of the action
}
}

• Step-3 : Create reducer const counter = (state=0, action) => {


switch(action.type){
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
}
}
let store = createStore(counter)

Create a Redux application


• Step-4 : display store on console
• store.subscribe(() => console.log(store.getState()))

• Step-5 : dispatch the action


• store.dispatch(increment()); //dispatches the increment action

• Step-6 : Execute the app.


Start server
• npm start
Need for Redux
• Redux offers a solution to storing all your application state in one place called
“Store”
• Components then “dispatch” state changes to store, not directly to other
components
• Components that need to be aware of state changes can “subscribe” to the store
• The center of every Redux application is the store. A "store" is a container that
holds your application's global state.
 A store is a JavaScript object with a few special functions and abilities that make it
different than a plain global object:
 You must never directly modify or change the state that is kept inside the Redux store
 Instead, the only way to cause an update to the state is to create a plain action object
that describes "something that happened in the application", and then dispatch the
action to the store to tell it what happened.
 When an action is dispatched, the store runs the root reducer function, and lets it
calculate the new state based on the old state and the action
 Finally, the store notifies subscribers that the state has been updated so the UI can be
updated with the new data.

Actions, reducers and dispatchers


• An action is a plain JavaScript object that has a type field. You can think of
an action as an event that describes something that happened in the
application.
 The type field should be a string that gives this action a descriptive name. Eg
"todoAdded“ or “depositFunds” or “incrementCounter”

• A reducer is a function that receives the current state and an action object,
decides how to update the state if necessary, and returns the new state:
(state, action) => newState.
 You can think of a reducer as an event listener which handles events based on the
received action (event) type.

• The Redux store has a method called dispatch. The only way to update the
state is to call store.dispatch() and pass in an action object.
 The store will run its reducer function and save the new state value inside, and we
can call getState() to retrieve the updated value:
My original index.js
//original React imports let store = createStore(counter);
import {createStore} from 'redux';
//Display it in console
//STORE -> GLOBALISED STATE store.subscribe(() =>
console.log(store.getState()));
//ACTION -> INCREMENT
const increment = () => { //DISPATCH
return { store.dispatch(increment());
type :'INCREMENT' //name of the action store.dispatch(decrement());
}
} ReactDOM.render(
const decrement = () => { <React.StrictMode>
return { <App />
type :'DECREMENT' //name of the action </React.StrictMode>,
} document.getElementById('root')
} );

//REDUCER
const counter = (state=0, action) => {
switch(action.type){
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
}
}

//reducers/counter.js
const counterReducer = (state=0, action) => { Create a Redux app
switch(action.type){
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1; //src/index.js
default: return null; import {createStore} from 'redux';
} import allReducers from "./reducers";
}
export default counterReducer; const store = createStore(allReducers);

//reducers/isLogged.js
const loggedReducer = (state=false, action) => {
switch(action.type){
case "SIGNIN": //reducers/index.js
return !state; import counterReducer from "./counter";
default: import loggedReducer from "./isLogged";
return state; import {combineReducers} from 'redux';
}
} const allReducers = combineReducers({
export default loggedReducer; counter : counterReducer,
isLogged:loggedReducer
})
export default allReducers;
//src/index.js
//Original code:
const store = createStore(allReducers);
//New code:
const store = createStore(allReducers,
window.__REDUX_DEVTOOLS_EXTENSION__ && windo
w.__REDUX_DEVTOOLS_EXTENSION__());

//src/index.js
import {createStore} from 'redux';
import allReducers from "./reducers"; const counterReducer =
import {Provider} from 'react-redux'; (state=0, action) => {…}

const myStore = createStore(allReducers,


window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

ReactDOM.render(
<React.StrictMode>
<Provider store={myStore}>
<App />
</Provider>
</React.StrictMode>,
App.js : displaying state Allows you to extract data
from the Redux store
state, using a selector
import './App.css'; function.
import {useSelector} from 'react-redux';

function App() {
const counter = useSelector(state => state.counter);
const isLogged = useSelector(state => state.isLogged);

return (
<div className="App"> I set the isLogged
<h1>Welcome to Redux</h1> state to true
<h3>Counter : {counter}</h3>
{isLogged ? <h3> Some valuable info here</h3> : ''}
</div>
);
}

export default App;

//actions/index.js
Modifying state export const increment = () => {
return {
type :'INCREMENT'
}
}
export const decrement = () => {
import './App.css';
return {
import {useSelector, useDispatch} from 'react-redux';
type :'DECREMENT'
import {increment} from './actions';
}
import {decrement} from './actions';
}
function App() {
const counter = useSelector(state => state.counter);
const isLogged = useSelector(state => state.isLogged);
const dispatch = useDispatch();

return (
<div className="App">
<h1>Welcome to Redux</h1>
<h3>Counter : {counter}</h3>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
{isLogged ? <h3> Some valuable info here</h3> : ''}
</div>
);
}
export default App;

You might also like