Decap472 Web Technologies
Decap472 Web Technologies
DECAP472
Edited by
Dr. Pawan Kumar
Web Technologies
Edited By:
Dr. Pawan Kumar
Title: WEB TECHNOLOGIES
Publisher Address: Lovely Professional University, Jalandhar Delhi GT road, Phagwara - 144411
ISBN: 978-93-94068-40-7
Objectives
After studying this unit, you will be able to:
Introduction
HTML 5 is a updation of the Hypertext Markup Language (HTML), which is a typical
programming language for displaying dynamic content on Web pages.
HTML5 was developed to remove the compatibility issue which was affecting the standard
HTML4. One of the major differences between HTML5 and its older versions was proprietary
plugins and APIs (for this web page built was tested in one browser as it may not run on another
browser). It allows providing an interactive interface for loading all types of elements easily. For
example, In HTML5 we need not install Flash plugins it will run by default in the browser.
On the other hand, HTML5 supports multimedia on mobile devices. New syntactic features were
introduced to support this, such as video, audio and canvas tags. HTML5 also introduces new
features which can really change the way users interact with documents including:
Example: HTML5 was implemented by the new working group of the World
WidHe TWMeLb5 Consortium (W3C) in 2007, as this group published the first public draft of
HTML 5 in January 2008.
The DOCTYPE
It is the older version of HTML with longer DOCTYPEs and the HTML language was based on the
SGML and mandatory to have a reference to a DTD.
Syntax used in HTML5 by authors to specify DOCTYPE and it is case sensitive.
<!DOCTYPEhtml>
Character Encoding
HTML5 Developers can use simple syntax for Character Encoding below-
<metacharset="UTF-8">
<scripttype="text/javascript"src="xyz.js"></script>
It is a common tag practiced to adda attribute having value “text/javascript” below is the syntax –
HTML 5 has made the tag simpler to use removing additional information syntax as below –
<scriptsrc="xyz.js"></script>
LINK tag
<linkrel="stylesheet"type="text/css"href="xyz.css">
HTML 5 has made the tag simpler to use removing additional information syntax as below –
<linkrel="stylesheet"href="stylefile.css">
<p>...</p>
HTMl5 tags are mostly case insensitive and can be written in all cases either uppercase, lower or
mixed case preferably lower case is recommended as a conventional method.
Utmost the elements in HTML5 have some content like <p>…</p> contains in paragraph.
Elements like br, hr, link, meta etc. are forbidden from containing any content at all and are known
as void elements
Some of the elements are shown below
Tag Description
<!--...--> Specifiesacomment
<!DOCTYPE> Specifiesthedocumenttype
<a> Specifiesananchor
<abbr> Specifiesanabbreviation
<address> Specifiesanaddresselement
<applet> Deprecated:Specifiesanapplet
numeric,hexidecimal,RG
Customattributes.AuthorsofaHTMLdocumentcan
definetheirownattributes.Muststartwith
data-XXXX UserDefined
"data-".
• Browser Setup.
• Your Working Folder.
• Creating an HTML File.
Generally, it's called local development when you create and test a website using only your own
computer. The setup required is called local environment setup. After you have set up your local
development environment, you can work on creating your own website with HTML & CSS
anytime and anywhere (even without an internet connection).
Text Editor
The two most essential tools for developing a website are a text editor and a browser. We'll start by
choosing and setting up a text editor. A text editor (or just "editor") is like the window in the center
of every lesson where you write your code. You'll need an editor to do any kind of programming,
not just HTML & CSS.
An HTML editor is a program for editing HTML, the markup of a web page. Although the HTML
markup in a web page can be controlled with any text editor, specialized HTML editors can offer
convenience and added functionality.
Browser Setup
Browsers are for viewing and displaying websites, like the one you're using to view this article
(most likely). There is a window on the right where the result of your HTML & CSS code is
displayed so you can see if it's correct.
Output:
Hello Welcome to HTML
Hello Welcome to HTML
Hello Welcome to HTML
This is a Paragraph
• “Normal text” surrounded by bracketed tags that tell browsers how to display web pages
• Pages end with “.htm” or “.html”
• HTML Editor – A word processor that has been specialized to make the writing of HTML
documents more effortless.
There are many different programs that you can use to create web documents. HTML Editors
enable users to create documents quickly and easily by pushing a few buttons. Instead ofentering
all of the HTML codes by hand. HTML Editors are excellent tools for experienced web developers;
however; it is important that you learn and understand the HTML language so that you can edit
code and fix “bugs” in your pages.
For this Course, we will focus on using the standard Microsoft Windows text editors, NotePad.
These programs will generate the HTML Source Code for you.
Starting Notepad
NotePad is the standard text editor that comes with the microsoft windows operating system. To
start NotePad in windows 9x or XP follow the steps bellow:
Click on the “Start” button located on your Windows task bar.
Click on “Programs” and then click on the directory menu labeled “Accessories”.
Locate the shortcut “NotePad” and click the shortcut once.
Now we can use the tags to implement a HTML5 document. The HEAD of your document point to
above window part. The TITLE of your document appears in the very top line of the user’s
browser. If the user chooses to “Bookmark” your page or save as a “Favorite”; it is the TITLE that is
added to the list.
The text in your TITLE should be as descriptive as possible because this is what many search
engines, on the internet, use for indexing your site. Document properties are controlled by
attributes of the BODY element. For example, there are color settings for the background color of
the page, the document’s text and different states of links.
Colors are set using “RGB” color codes, which are, represented as hexadecimal values. Each 2-digit
section of the code represents the amount, in sequence, of red, green or blue that forms the color.
For example, a RGB value with 00 as the first two digits has no red in the color.
NetBeans
NetBeans is an open source IDE is used for developing software applications by developers. It can
read and edit texts in HTML. PHP, C++ and a few more. It provides an intuitive user interface for
macOS 10.14 users and comes with customized key-bindings. Interestingly, it supports Git and
management of source codes.
Sublime Text 2
Sublime Text 2 is the minimalistic favorite of developers, because it can easily be completely
customized to one’s own needs by using a JSON file. Moreover, there are several extensions to
“stretch” the editor with. For example, a must-have extension is Package Control, which you can
use to easily find and install extensions and plug-ins from right within the editor. To describe the
full extent of features of Sublime Text 2 is rather difficult, as it can do, through its plug-ins and
extensions, basically anything you need it to do.
Brackets
Brackets is a modern open source editor with several extremely interesting features. For example,
when used in combination with Adobe Creative Cloud Extract (=preview) it can read design data
such as colors, types, histories etc. directly from a PSD file and transform it into minimalistic,
correct CSS code
Atoms
Atom is an open-source and free to use text and code editor with a rich set of plug-ins for different
functions. It can be downloaded from Atom homepage, and it runs on Microsoft Windows, macOS,
and Linux distributions. Atom highlights code written in many languages, including HTML, Java,
Python, and others. Sample HTML code displayed in the Atom editor is shown in Figure
Notepad++
Notepad++ is a free-to-use editor that supports several programming languages. It runs on
Microsoft Windows and doesn't have packages for other operating systems. You can download
Notepad++ from Notepad++ home.
GitHub
To be very crisp about what exactly is GitHub, it is a file or code-sharing service to collaborate with
different people.
GitHub is a highly used software that is typically used for version control.
It is helpful when more than just one person is working on a project. Say for example, a software
developer team wants to build a website and everyone has to update their codes simultaneously
while working on the project. In this case, Github helps them to build a centralized repository
where everyone can upload, edit, and manage the code files.
GitHub Repository
A repository is a storage space where your project lives. It can be local to a folder on your
computer, or it can be a storage space on GitHub or another online host. You can keep code files,
text files, images or any kind of a file in a repository.
You need a GitHub repository when you have done some changes and are ready to be uploaded.
This GitHub repository acts as your remote repository.
• Go to the link: https://github.com/ . Fill the sign up form and click on “Sign up for
Github”.
• Click on “Start a new project”.
Now, if you noticed by default a GitHub repository is public which means that anyone can view the
contents of this repository whereas in a private repository, you can choose who can view the
content.
Also, private repository is a paid version. Also, if you refer the above screenshot, initialize the
repository with a README file. This file contains the description of the file and once you check this
box, this will be the first file inside your repository
Summary
• Hypertext refers to the way in which Web pages (HTML documents) are linked together.
Thus, the link available on a webpage is called Hypertext.
• HTML makes it possible to organize and format documents, similarly to Microsoft Word.
• Web technology is a standard that allows you to develop web applications with the help of
pre- defined sets of classes, objects, methods, and properties available in a markup language,
style sheet language, or programming language.
• A link relation is a relation between two files. HTML5 allow you to link your HTML
document with another document or file.
• Elements are the building blocks of an HTML document. An element instructs the web
browser how to display the HTML document on the user’s screen.
• Root elements represent the main or the starting element that should be present in all HTML
document.
• The DOM is a cross-platform and language-independent interface that allows programs and
scripts to dynamically access and update the content, structure, and style of HTML or XML
documents.
Keywords
Hypertext: Text (it often has embedded images, videos etc.) that is organized in order to link related
items
Markup: A style guide for formatting whatsoever to be printed in hardcopy or soft copy format
HTML 5 is a updation of the Hypertext Markup Language (HTML), which is a typical
programming language for displaying dynamic content on Web pages
DOCTYPEs It is the older version of HTML with longer DOCTYPEs
Class Classifies an element for use with Cascading Style Sheets
Data-XXXX Custom attributes. Authors of a HTML document can define their own attributes. Must
start with “data”.
NetBeans is an open-source IDE is used for developing software applications by developers.
GitHub To be very crisp about what exactly is GitHub, it is a file or code-sharing service to
collaborate with different people
SelfAssessment
1. What are core components of Web applications?
2. makes every addressable item in a web application an Object that can be manipulated for
color, transparency, position, sound and behaviors.
A. Window Object
B. Document Object
C. Form Object
D. Link Object
A. window Object
B. Document Object
C. Form Object
D. Link Object
A. window Object
B. Document Object
C. Form Object
D. Link Object
8.In MVC Where changes to the page are rendered and displayed
A.Model
B.View
C.Control
D.All of the above
11. React renders HTML to the web page by using a function called
A. HTML code
B. HTML element
C. Both of above
D. None of the above
A. JavaScript XML
B. javascript
C. XML
D. None of a above
A. Components
B. Properties
C. States
D. Classes
6. C 7. C 8. B 9. A 10. A
Review Questions:
1. What is the difference between HTML and HTML5?
2. What is <!DOCTYPE>? What are the different types of <!DOCTYPE> that are available?
3. What are the advantages of using HTML5?
4. How to create a link that will connect to another web browser page when clicked in
HTML5? Explain with example.
5. What were some of the key goals and motivations for the HTML5 specification?
6. Can a <section> contain <article> elements? Can an <article> contain <section> elements?
Provide usage examples
Further Readings
HTML 5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery) 2Ed.
Web Enabled Commercial Application Development Using HTML, JavaScript, DHTML
and PHP (4th Revised Edition)
Web Links
https://www.tutorialspoint.com/index.htm www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
• DiscusstheHistoryofHTML5
• Discuss SVG
Introduction
HTML5 is a markup language that was founded in 2004 by the Web Hypertext Application
Technology WorkingGroup (WHATWG) whose members include Apple, Mozilla Foundation
and Opera Software. Then in Oct 2006 W3C(World Wide Web Consortium) decided to stop
their work on XHTML and start collaborating with "WHATWG"
todevelopHTMLasatechnology.Afterthat,thefirstversionofHTML5waspublishedin2008thatwas
writtenbyIanHickson,Google,[email protected]'snotcompletedandchangesarestillremainingbec
auseaccordingtoWHATWGexperts "HTML5 is a continually evolving technology that will never
end". After the first draft of HTML5, it's time
tomakecompatiblebrowsersthatsupportHTML5features.AndthenMozillatookthefirststepandintrodu
ced'Firefox3' which allows users to view HTML5 in the browser, but Safari, Google Chrome, and
IE were far behind in supportof HTML5 features in their browsers. HTML5 was gaining
popularity day by day. Then in April 2010, Steve Jobsdeclared that flash will never be allowed
on Apple's smart devices. He said that "Flash was designed for PCs using amouse, not for touch
WEB TECHNOLOGIES
screens using fingers". This statement is enough to change the mind of many companies
andthat'sthereasontheybeganthedevelopmentofHTML5.
Ithasintroducednewmultimediafeatureswhichsupportaudioandvideocontrolsbyusing
<audio>and<video>tags.
Therearenewgraphicselementsincludingvectorgraphicsandtags.
Enrichsemanticcontentbyincluding<header><footer>,<article>,<section>and<figure>
areadded.
DragandDrop-Theusercangrabanobjectanddragit furtherdroppingittoanewlocation.
Geo-locationservices-Ithelpstolocatethegeographicallocationofaclient.
Webstoragefacilitywhichprovideswebapplicationmethodstostoredataona webbrowser.
UsesSQLdatabasetostoredataoffline.
Allowsdrawingvariousshapesliketriangles,rectangles,circles,etc.
Capableof handlingincorrectsyntax.
EasyDOCTYPEdeclarationi.e.,<!doctypehtml>
Easycharacterencodingi.e.,<metacharset=”UTF-8″>
″>
Doctypedeclarationinhtmlistoolong The
<!DOCTYPEHTMLPUBLIC"-//W3C DOCTYPEdeclaratio
Doctype //DTDHTML4.01//EN" ninhtml5isverysimp
"http://www.w3.org/TR/html4/strict.dtd"> le"<!DOCTYPEhtml>
Characterencodi
Character encodinginHTMListoolong.
CharacterEncod ngdeclarationiss
<!DOCTYPEHTMLPUBLIC"-//W3C//
ing imple<metacha
DTDHTML4.0Transitional//EN"> rset="UTF-8">
Audioandvideoarees
Multimedia Audio and video are not the part sentialpartsofHTML
support ofHTML4. 5,like:<Audio>,<Vid
eo>.
DidyouKnow? : HTML5 provides you with more features with respect to the HTML such as
audio, video with the helpoftags,dragand dropfeature,Geolocation,browsersupport,etc.
WEB TECHNOLOGIES
2.3 AnatomyofanHTMLTag
HTMLconsistsof aseriesofelements, which you use toenclose,or wrap,differentparts ofthe
contenttomake itappear acertain way, or act acertain way. The enclosingtagscan make aword or
image hyperlink to somewhere
elsecanitalicizewords,canmakethefontbiggerorsmaller,andsoon.Forexample,HypertextMarkupLan
guage
Ifwewantedthelinetostandbyitself,wecouldspecifythatit isaparagraphbyenclosingit
inparagraphtags:
<p>HypertextMarkupLanguage</p>
Theopeningtag: Thisconsistsof the nameof the element(in this case, p), wrapped inopening
andclosing angle brackets. This states where the element begins or starts to take effect in this case
where theparagraphbegins.
The closing tag: This is the same as the opening tag, except that it includes a forward slash before the
elementname.Thisstateswheretheelementends—
inthiscasewheretheparagraphends.Failingtoaddaclosingtag isoneof thestandardbeginnererrors
andcanlead to strange results.
Thecontent:Thisisthecontentoftheelement,whichinthiscase,isjusttext.
Theelement:Theopeningtag,theclosingtag,andthecontenttogethercomprisetheelement.
Elementscanalsohaveattributes thatlooklikethe following:
Attributescontainextrainformationabouttheelementthatyoudon'twanttoappear intheactual
content.Here, class istheattribute name and editor-note aretheattribute value.The class
attributeallowsyoutogivetheelement a non-unique identifier that can be used to target it (and any
other elements with the same class value) withstyleinformationandotherthings.
1. A space between it and the element name (or the previous attribute, if the element already
has one or moreattributes).
2. Theattributenameisfollowedbyanequalsign.
3. Theattributevalueiswrappedbyopeningandclosingquotationmarks .
Note:Simpleattributevaluesthatdon'tcontainASCIIwhitespace.
2.4 HTMLDocumentStructure
The <HTML>is a markup language that is used by the browser to manipulate text, images, and
other content todisplayitintherequiredformat.
Tags in HTML: Tags are one of the most importantparts ofan HTML Document. HTML uses some
predefinedtagswhichtellthebrowseraboutcontentdisplayproperty,thatishowtodisplayaparticularly
givencontent
In itssimplestform,thefollowingisanHTMLdocument:
TheDOCTYPE
TheDOCTYPEtellsthewebbrowserwhichversionofHTMLthepageiswrittenin.Inth
isclass,wewillbeusing‘XHTMLTransitional’,whichallowsusalittleflexibility.
The<html>Element
The<html>element tellsthebrowserthat the pagewill be formatted in HTML and,
optionally,whichworldlanguagethepagecontentisin.
The<head>and<body>Elements
The<head>elementsurroundsallthespecial“behindthescenes”elementsofawebdo
cument.Mostoftheseelementsdonotgetdisplayeddirectlyonthewebpage.
The <body> element surrounds all the actual content (text, images, videos,
links, etc.) thatwill bedisplayedonourwebpage.
The<meta>Element
Immediatelyafterthe<head>line,weplacethis<meta>element:
ThislinedeclaresthatthedocumentisencodedintheUTF-8(Unicode)characterset.
Therecanbemultiple<meta>linesonthesamewebpage.The<meta>elementisoftenu
sedtoprovideadditionalinformationsuchaspagekeywords,apagedescription,andt
heauthor(s)ofawebdocument.
WEB TECHNOLOGIES
The<title>Element
The<title>elementdefineswhattextwillshowinthewebbrowser’stitlebar:
ModernHTMLspecificationssplitthesetwocontentmodelsintosevenmodels.
Metadata:Metadatacontentisresponsibleforsettingupthepresentation(look)orbehaviortothe
restoftheHTMLpage.ItcanalsosetuptherelationshipoftheHTMLdocumentwithother
documents.
<!doctypehtml>
<htmllang="en">
<head>
<metaname=”application-name”content=”HTML5forbeginners”>
</head>
<body>
</body>
</html>
Flowcontent:Most contents of HTML documents arein this type. These contents influence other
contentsto flow. Sectioning content represents a section in the current document. Each sectioning
content potentiallyhasaheadingcontentand footer.
Heading Content: Heading Content is used to provide different heading levels in
HTML documents.Thesecontentsareusedtocreateheadlinesforatext.
Forexample,ifyouwanttodisplayanarticleonyourHTMLpage,thearticleiswritteninnormalpl
aintext,but itstitle is written in bold and large text. In this case, you can use the heading
elements to make the title distinct fromthe remainingtext.Aheadingcontentisdefinedas-
h1,h2,h3,h4,h5,h6,group.
Embedded content: Embedded content embeds resources from other sources or adds
content from othermark-uplanguages.Forexample,imagevideos,etc.
TheHTMLelementsthatcancontainembeddedcontentare-
audio,canvas,embed,iframe,img,math,object,svg,video
2.6 HTMLCharacterEntity
HTMLsymbolslikemathematicaloperators,arrows,technicalsymbols,andshapes,arenotp
resentonanormal keyboard.
ReservedcharactersinHTMLmustbereplacedwithcharacterentities.
SomecharactersarereservedinHTML.
Ifyouusethelessthan(<)orgreaterthan(>)signsinyourtext,thebrowsermightmixthemwithtags
.
CharacterentitiesareusedtodisplayreservedcharactersinHTML.0.character
entitylookslikethis:
&entity_name;
OR
&#entity_number;
Todisplayalessthansign(<)wemustwrite:<or<
Advantageofusinganentityname:Anentitynameiseasytoremember.
Adisadvantageofusinganentityname:Browsersmaynotsupportallentitynames,butthesupportforenti
tynumbersisgood.
WEB TECHNOLOGIES
<a href="https://www.w3schools.com/">Visit W3Schools.com!</a>
By default, the linked page will be displayed in the current browser window. To change this, you
must specify another target for the link. The target attribute specifies where to open the linked
document.
The target attribute can have one of the following values:
_self - Default. Opens the document in the same window/tab as it was clicked
_blank - Opens the document in a new window or tab
_parent - Opens the document in the parent frame
_top - Opens the document in the full body of the window
2.8 Canvas
The HTML5 canvas element can be used to draw graphics on the webpage via JavaScript. The
canvas was originally introduced by Apple for the Mac OS dashboard widgets and to power
graphics in the Safari web browser. Later it was adopted by Firefox, Google Chrome, and Opera.
Now the canvas is a part of the new HTML5 specification for next-generation web technologies. By
default, the <canvas> element has 300px of width and 150px of height without any border and
content. However, custom width and height can be defined using the CSS height and width
property whereas the border can be applied using the CSS border property.
HTML5 Canvas
The HTML5 Canvas is an Immediate Mode bit-mapped area of the screen that can be manipulated
with JavaScript and CSS. The HTML5 Canvas is an Immediate Mode bit-mapped area of the screen
that can be manipulated with JavaScript and CSS.
Immediate Mode
Immediate Mode refers to the way the canvas renders pixels on the screen. The HTML5 Canvas
completely redraws the bitmapped screen on every frame using Canvas API calls from JavaScript.
As a programmer, your job is to set-up the screen display before each frame is rendered.
Flash, Silverlight, and DOM <div> manipulation techniques use Retained Mode. In Retained
Mode a list of individual display objects is stored and manipulated.
width
height
id
Width and height read/write which means you can resize the Canvas on the fly
Output:
2.9 SVG
SVG stands for Scalable Vector Graphics. SVG is used to define graphics for the Web.SVG is a W3C
recommendation
Example:
<!DOCTYPE html>
<html>
<body>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
WEB TECHNOLOGIES
</body>
</html>
Summary
HTML is a markup language that is used for creating attractive web pages with the help of
styling, and which looks in a nice format on a web browser.
HTML tags are like keywords define that how a web browser will format and display the
content.
If You have used an open tag <tag>, then you must use a close tag </tag>.
HTML attributes are special words that provide additional information about the elements
Each element or tag can have attributes, which define the behavior of that element.
<canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be
used to draw graphs, make photo compositions, or do simple (and not so simple)
animations.
SVG stands for Scalable Vector Graphics and it is a language for describing 2D graphics
and graphical applications in XML and the XML is then rendered by an SVG viewer.
SVG is mostly useful for vector type diagrams like Pie charts, Two-dimensional graphs in
an X, Y coordinate system, etc.
Keywords
DOCTYPE:tellsthewebbrowserwhichversionofHTMLthepageiswrittenin.Inthis
class,wewillbeusing‘XHTMLTransitional’,whichallowsusalittleflexibility.
The<head>elementsurroundsallthespecial“behindthescenes”elementsofawebdo
cument.Mostoftheseelementsdonotgetdisplayeddirectlyonthewebpage.
The <body> element surrounds all the actual content (text, images, videos,
links, etc.) thatwill bedisplayedonourwebpage.
is displayed on the browser in bold format and the size of the text depends on
the number of headings.
Self Assessment
1. Which of the following tag is used to define options in a drop-down selection list?
A. <select>
B. <list>
C. <dropdown>
D. <option>
6. Which of the following HTML tag is used to display the text with scrolling effect?
A. <marquee>
B. <scroll>
C. <div>
D. None of the above
9. Which of the following is the correct way to create a list using the lowercase letters?
A. <ol alpha = "a" >
WEB TECHNOLOGIES
B. <ol type = "a">
C. <ol letter = "a">
D. None of the above
10. Which of the following HTML attribute is used to define inline styles?
A. style
B. type
C. class
D. None of the above
B. .html
C. .hml
15. Which of the following is the correct way to create a list using the lowercase letters?
A. <ol alpha = "a" >
B. <ol type = "a">
C. <ol letter = "a">
D. None of the above
6. A 7. C 8. A 9. B 10. A
Review Questions
1. What are some of the key new features in HTML5?
2. What are the different new form element types in HTML 5?
3. Explain the layout of HTML?
4. What were some of the key goals and motivations for the HTML5 specification?
5. How to create a hyperlink in HTML
6. What is the canvas element in HTML5?
7. What’s the difference between the <svg> and <canvas> elements?
8. Give a simple implementation of the <video> tag to embed a videostored
at http://www.example.com/amazing_video.mp4. Give the video width of 640 pixels by 360
pixels.
Further Readings
HTML5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, j Query)
2Ed.
Web Enabled Commercial Application Development Using HTML, Java Script,
DHTML and PHP (4th Revised Edition)
Trevor Burnham. Async JavaScript. The Pragmatic Bookshelf, Raleigh, NC and
Dallas, TX, 2012.
Objectives
After studying this unit, you will be able to:
Introduction to CSS3
Discuss the selectors present in the syntax of a CSS file
How to work CSS3
Learn about how to insert CSS ai an HTML document.
Introduction
CSS is used to control the style of a web document in a simple and easy way.
CSS is the acronym for "Cascading Style Sheet".
Cascading Style Sheets fondly referred to as CSS, is a simple design language intended to simplify
the process of making web pages presentable.
CSS is a MUST for students and working professionals to become great Software Engineers
especially when they are working in Web Development Domain.
Web Technologies
CSS saves time − You can write CSS once and then reuse the same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages as
you want.
Easy maintenance − To make a global change, simply change the style, and all elements in all
the web pages will be updated automatically.
Global web standards − N ow HTML attributes are being deprecated and it is being
recommended to use CSS. So, it's a good idea to start using CSS in all the HTML pages to
make them compatible with future browsers.
Platform Independence − The Script offers consistent platform independence and can support
the latest browsers as well.
Whylearn CSS?
Create a Stunning Website - CSS handles the look and feel part of a web page. Using CSS, you can
control the color of the text, the style of fonts, the spacing between paragraphs, how columns are
sized and laid out, what background images or colors are used, layout designs, variations in
display for different devices and screen sizes as well as a variety of other effects.
Become a web designer - If you want to start a career as a professional web designer, HTML and
CSS designing is a must skill.
Control web - CSS is easy to learn and understand but it provides powerful control over the
presentation of an HTML document. Most commonly, CSS is combined with the markup languages
HTML or XHTML.
Learn other languages - Once you understand the basics of HTML and CSS then other related
technologies like JavaScript, PHP, or angular have become easier to understand.
Applications of CSS
CSS saves time - You can write CSS once and then reuse the same sheet in multiple HTML pages.
You can define a style for each HTML element and apply it to as many Web pages as you want.
Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every time.
Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means
faster download times.
Easy maintenance - To make a global change, simply change the style, and all elements in all the
web pages will be updated automatically.
Superior styles to HTML - CSS has a much wider array of attributes than HTML, so you can give a
far better look to your HTML page in comparison to HTML attributes.
Multiple Device Compatibility - Style sheets allow content to be optimized for more than one type
of device. By using the same HTML document, different versions of a website can be presented for
handheld devices such as PDAs and cell phones or for printing.
Global web standards - Now HTML attributes are being deprecated and it is being recommended
to use CSS. So, it’s a good idea to start using CSS in all the HTML pages to make them compatible
with future browsers.
Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like
<h1> or <table> etc.
Property − A property is a type of attribute of an HTML tag. Put simply, all the HTML attributes
are converted into CSS properties. They could be color, border etc.
Value − Values are assigned to properties. For example, color property can have value either red or
#F1F1F1 etc.
Example,
Web Technologies
h1 {
color: #36CFFF;
}
The Universal Selectors
Rather than selecting elements of a specific type, the universal selector quite simply matches the
name of any element type −
*{
color: #000000;
}
This rule renders the content of every element in our document in black.
The Descendant Selectors
Suppose you want to apply a style rule to a particular element only when it lies inside a particular
element. As given in the following example, the style rule will apply to the <em> element only
when it lies inside <ul> tag.
ulem {
color: #000000;
}
The Class Selectors
You can define style rules based on the class attribute of the elements. All the elements having that
class will be formatted according to the defined rule.
.black {
color: #000000;
}
This rule renders the content in black for every element with a class attribute set to black in our
document.
Example
You can make it a bit more particular. For example −
h1.black {
color: #000000;
This rule renders the content in black for only <h1> elements with class attribute set to
black.
You an apply more than one class selector to given element. Consider the following
example −
−
</p>
Attributes
Attributes associated with <style> elements are –
Web Technologies
You can use the style attribute of any HTML element to define style rules. These rules will be
applied to that element only. Here is the generic syntax −
<element style = "...style rules....">
style style rules The value of the style attribute is a combination of style
declarations separated by semicolons (;).
Example
<html>
<head>
</head>
<body>
<h1 style = "color:#36C;">
This is inline CSS
</h1>
</body>
</html>
The <link> element can be used to include an external stylesheet file in your HTML
document.
An external style sheet is a separate text file with .CSS extension. You define all the Style rules
within this text file and then you can include this file in any HTML document using <link>
element.
Here is the generic syntax of including external CSS file −
<head>
<link type = "text/css" href = "..." media = "..." />
</head>
Attributes
media Screentvprojection
Specifies the device the document will be
Handheldprint displayed on. The default value is all. This
is an optional attribute
Brailleauralall
Example,
Consider a simple style sheet file with a name mystyle.css having the following rules −
h1, h2, h3 {
color: #36C;
font-weight: normal;
letter-spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
Now you can include this file mystyle.css in any HTML document as follows −
<head>
</head>
@Import is used to import an external stylesheet in a manner similar to the <link> element.
Here is the generic syntax of @import rule.
<head>
@import "URL";
</head>
Here URL is the URL of the style sheet file having style rules. You can use another syntax as
well −
<head>
@importurl("URL");
</head>
CSS Colors
Colors in CSS can be specified by the following methods:
Hexadecimal colors
Hexadecimal colors with transparency
RGB colors
RGBA colors
HSL colors
HSLA colors
Web Technologies
Hexadecimal Colors
A hexadecimal color is specified with: #RRGGBB, where the RR (red), GG (green) and BB (blue)
hexadecimal integers specify the components of the color. All values must be between 00 and FF.
For example, the #0000ff value is rendered as blue, because the blue component is set to its
highest value (ff) and the others are set to 00.
Example,
different HEX colors:
#p1 {background-color: #ff0000;} /* red */
#p2 {background-color: #00ff00;} /* green */
#p3 {background-color: #0000ff;} /* blue */
RGB Colors
An RGB color value is specified with the rgb() function, which has the following syntax:
rgb(red, green, blue)
Each parameter (red, green, and blue) defines the intensity of the color and can be an integer
between 0 and 255 or a percentage value (from 0% to 100%).
For example, the rgb(0,0,255) value is rendered as blue, because the blue parameter is set to its
highest value (255) and the others are set to 0.
Also, the following values define equal color: rgb(0,0,255) and rgb(0%,0%,100%)
RGBA Colors
RGBA color values are an extension of RGB color values with an alpha channel - which specifies the
opacity of the object.
An RGBA color is specified with the rgba() function, which has the following syntax:
rgba(red, green, blue, alpha)
HSL Colors
HSL stands for hue, saturation, and lightness - and represents a cylindrical-coordinate
representation of colors.
An HSL color value is specified with the hsl() function, which has the following syntax:
hsl(hue, saturation, lightness)
Example
Web Technologies
Summary
Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a
document written in HTML.
You declare a CSS class by using a dot (.) followed by the class name. You make the class
name yourself. After the class name, and then enter the properties/values that you want to
assign to your class.
It supports more colors and a wide range of color definitions.
It allows you to change the style of the same HTML file in which you are working.
Cascading Style Sheets fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable
Allows Multiple backgrounds on a web page.
Its display shadow with the text.
Provides an easy and quick to add a style sheet to a web page. You do not need to create the
whole pager or edit a new element in the head of your document.
Displays the Web page only after the entire style sheet is loaded.
Keywords
CSS: stands for Cascading Style Sheets.
Selectors:CSS selectors are used to "find" (or select) the HTML elements.
Style:element contains style information for a document or part of a document.
Href:Specifies the location of the linked document.
@Import is used to import an external stylesheet in a manner similar to the <link> element. Here is
the generic syntax of the @import rule.
Self Assessment
1. Which of the following property is used as the shorthand property for the padding
properties?
A. padding-left
B. padding-right
C. padding
D. All of the above
5. A CSS_____ are used to selecting HTML elements based on their element name, id, attributes,
etc
A. Selectors
B. Syntax
C. Value
D. None of these
8. Which of the following is the correct syntax for referring the external style sheet?
A. <style src = example.css>
B. <style src = "example.css" >
C. <stylesheet> example.css </stylesheet>
D. <link rel="stylesheet" type="text/css" href="example.css">
10. The property in CSS used to change the text color of an element is –
A. bgcolor
Web Technologies
B. color
C. background-color
D. All of the above
A. text-style
B. text-size
C. font-size
D. None of the above
14. Which of the following CSS property is used to set the background image of an element?
A. background-attachment
B. background-image
C. background-color
D. None of the above
15. Which of the following is the correct syntax to make the background-color of all paragraph
elements to yellow?
A. p {background-color : yellow;}
B. p {background-color : #yellow;}
C. all {background-color : yellow;}
D. all p {background-color : #yellow;}
6. A 7. C 8. D 9. C 10. B
Review Questions
1. What are the different ways you could integrate CSS into your HTML page?
2. What is the difference between the usage of an ID and a Class?
3. Elaborate the function of inline CSS with an example?
Further Readings
HTML5 Black Book (Covers CSS3, JavaScript, XML, XHTML, AJAX, PHP, jQuery)
2Ed.
Web Enabled Commercial Application Development Using HTML, JavaScript,
DHTML and PHP (4th Revised Edition)
Trevor Burnham. Async JavaScript. The Pragmatic Bookshelf, Raleigh, NC and
Dallas, TX, 2012.
Parminder Kaur, Lovely Professional University Unit 04: CSS Class and ID
Objectives
After studying this unit, you will be able to:
Introduction
In this chapter, we will understand the basic ingredients of CSS are the selectors, properties, and
values. A CSS document can contain multiple selectors and a selector can have multiple properties
which in turn can have a value consisting of one or several elements, we also learned about pseudo-
classes, A Pseudo class in CSS is used to define the special state of an element. It can be combined
with a CSS selector to add an effect to existing elements based on their states. Anatomy of CSSRule.
CSS3 allows you to set the color of the background on the basis of various color specifications. It
also enables you to set the transparency level of a color that has to be displayed in the background
of an element.
Rules or rulesets
Selectors
Declarations
Properties
Web Technologies
ID selectorThe ID selector matches an element based on the value of its id attribute. In order for the
element to be selected, its ID attribute must exactly match the value given in the selector. The #
symbol and the id of the HTML element name are used to select the desired element.
The difference between an ID and a class is that an ID is only used to identify one single
element in our HTML. IDs are only used when one element on the page should have a
particular style applied to it. However, a class can be used to identify more than one HTML
element.
Web Technologies
Selector: pseudo-class
{
Property: value;
}
Important points
While defining pseudo-classes in a <style>...</style> block, following points should be noted −
a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.
a:active MUST come after a:hover in the CSS definition in order to be effective.
Pseudo-class names are not case-sensitive.
Pseudo-class are different from CSS classes but they can be combined.
Links can be displayed in different ways:
/* unvisited link */
a:link {
color: #FF0000;
}
/* visited link */
a:visited {
color: #00FF00;
}
/* mouse over link */
a:hover {
color: #FF00FF;
}
/* selected link */
a:active {
color: #0000FF;
}
Pseudo-classes and HTML Classes
Web Technologies
{
background-color: blue;
}
Simple Tooltip Hover
Hover over a <div> element to show a <p> element (like a tooltip):
Example
p{
display: none;
background-color: yellow;
padding: 20px;
}
div:hover p {
display: block;
}
What are Pseudo-Elements?
A CSS pseudo-element is used to style specified parts of an element.
For example, it can be used to:
Style the first letter, or line, of an element
Insert content before, or after, the content of an element
The syntax of pseudo-elements:
Selector::pseudo-element {
property: value;
}
STICKY INITIAL
Static Default value. Elements render in order, as they appear in the document flow.
Absolute:The element is positioned relative to its first positioned (not static) ancestor element.
Fixed: The element is positioned relative to the browser window
Relative: The element is positioned relative to its normal position, so "left:20px" adds 20 pixels to
the element's LEFT position.
Sticky:The element is positioned based on the user's scroll position.
Example
h2.pos_left
{
position: relative;
left: -20px;
}
h2.pos_right
{
position: relative;
left: 20px;
}
StaticA static positioned element is always positioned according to the normal flow of the
page. HTML elements are positioned static by default. Statically positioned elements are not
affected by the top, bottom, left, right, and z-index properties.
AbsoluteAn absolutely positioned element is positioned relative to the first parent element
that has a position other than static. If no such element is found, it will be positioned on a
page relative to the 'top-left' corner of the browser window. The box's offsets further can be
specified using one or more of the properties tops, right, bottom, and left.
Web Technologies
Initial
Serif fonts have a small stroke at the edges of each letter. They create a sense of formality and
elegance.
Sans-serif fonts have clean lines (no small strokes attached). They create a modern and
minimalistic look.
Monospace fonts - here all the letters have the same fixed width. They create a mechanical
look.
Cursive fonts imitate human handwriting.
Fantasy fonts are decorative/playful fonts.
Example
p1 {
font-family: "Times New Roman", Times, serif;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
}
.p3 {
font-family: "Lucida Console", "Courier New", monospace;
}
Google Fonts
If you do not want to use any of the standard fonts in HTML, you can use Google Fonts.
Google Fonts are free to use and have more than 1000 fonts to choose from.
How To Use Google Fonts
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Sofia">
<style>
body {
font-family: "Sofia", sans-serif;
}
</style>
</head>
Web Technologies
Summary
CSS is a set of rules which consist of a selector and adeclaration.
A selector is used to select the element and apply styles too, and a declaration isthe
combination of a property and a value for that element.
Selectors are the conditions of a CSS ruleset. Theselectors come from theircapability to be
combined, allowing you to create very specific conditions, applying styles
only to the exact element.
IDs and classes, which are attributes of an HTML element, that allowsbeing more
specificwhen styling elements.
Sometimes you may want to apply a style to more than one element, then you can use the
group selectors.
Dynamic pseudo-classes allow you to style an element.
Borders are graphical elements that apply the edge of an element.
We can use color values and functions to access more than 16 million colors, theyare RGB and
HSL.
Keywords
CSS property is basically responsible for the exact style that you want to apply to the target
element.
Class SelectorThe class selector selects elements with a specific class attribute. It matches all the
HTML elements based on the contents of their class attribute.
ID selector The ID selector matches an element based on the value of its id attribute.
CSS border properties allow you to specify the style, width, and color of an element's border
Static Default value. Elements render in order, as they appear in the document flow.
Absolute: The element is positioned relative to its first positioned (not static) ancestor element.
Fixed: The element is positioned relative to the browser window
Relative: The element is positioned relative to its normal position, so "left:20px" adds 20 pixels to
the element's LEFT position.
Sticky: The element is positioned based on the user's scroll position.
Self Assessment
1. A____ is an HTML tag at which a style will be applied. This could be any tag like <h1> or
<table> etc.
A. Selector
B. Property
C. Value
D. None of these
D. None of these
3. ______are assigned to properties. For example, color property can havether red or #F1F1F1
etc
A. Selector
B. Property
C. Value
D. None of these
4. The _______specifies whether the browser should control the appearance of the adjacent
borders that touch each other or whether each cell should maintain its style
A. border-collapse
B. border-spacing
C. Both of these
D. None of these
5. The _______specifies the width that should appear between table cells.
A. border-collapse
B. border-spacing
C. Both of these
D. None of these
A. normal
B. small-caps
C. large-caps
D. inherit
7. Which of the following CSS property is used to specify whether the table cells share the
common or separate border?
A. border-collapse
B. border-radius
C. border-spacing
D. None of the above
8. The CSS property used to make the rounded borders, or rounded corners around an element
is -
A. border-collapse
B. border-radius
C. border-spacing
D. None of the above
A. <css>
B. <!DOCTYPE html>
C. <script>
Web Technologies
D. <style>
10. Which of the following CSS selectors are used to specify a group of elements?
A. tag
B. id
C. class
D. both class and tag
14. The _______property specifies the type of positioning method used for an element.
A. Placing
B. Position
C. Accurate
D. None of these
15. An ______positioned element is positioned relative to the first parent element that has a
position other than static.
A. Absolutely
B. Relatively
C. Static
D. All of the above
l. A 2. B 3. C 4. A 5. B
6. C 7. A 8. B 9. D 10. C
Review Questions
1. Define the use of the ruleset.
2. Can we include the multiple CSS3 files in one HTML document? Explain?
3. What is the difference between the usage of an ID and a Class?
4. Elaborate the function of inline CSS with an example?
5. What are pseudo-elements in CSS? Explain with some code?
6. How would you define the Pseudo-classes in CSS3?
7. How many ways can a CSS be integrated as a web page?
8. Define the property used for image scroll controlling?
9. What are the differences between relative and absolute in CSS? Explain?
Further Readings
HTML5BlackBook(CoversCSS3,JavaScript,XML,XHTML,AJAX,PHP,jQuery)2Ed.
WebEnabledCommercialApplicationDevelopmentUsingHTML,JavaScript,DHTMLa
ndPHP(4thRevisedEdition)
Trevor Burnham. Async JavaScript. The Pragmatic Bookshelf, Raleigh, NC and
Dallas, TX, 2012.
Parminder Kaur, Lovely Professional University Unit 05: Advanced Topics of CSS3
Objectives
After studying this unit, you will be able to:
Introduction
In this chapter,you learn about Styling Text, The Box Model, Outline Property, and Positioning
elements. The box model and various aspects related to it. Such as margin, padding, width, and
border. Next, we will learn about different backgrounds, colors, and gradient effects on your web
pages. You learn about different background properties, such as background-position and
background-repeat, and how to set multiple background values on a single web page. Next will
discuss positioning elements, InCSS helps you to place your HTML element. You can put any
HTML element at whatever location you like. You can require whether you want the element
positioned relative to its natural position on the page or absolute based on its parent element.
Font styles: Properties that affect a text's font, e.g., which font gets applied, its size, and
whether it's bold, italic, etc.
Web Technologies
Text layout styles: Properties that affect the spacing and other layout features of the text,
allowing manipulation of, for example, the space between lines and letters, and how the text is
aligned within the content box.
CSS provides three values for setting the font styles of text: normal, oblique, and italic. The normal
style displays the text in upright and straight letters, oblique displays the text in slanting or
learning letters, and italic displays the text in italic letters.
<style>
P{
Font-size:20px;
}
Span.normal {
Font-style:normal;
{
Span.italic{
Font-style:italic;
}
Span.oblique{
Font-style:oblique;
}
</style>
The text-align property is used to control how text is aligned within its holding content box. The
following possible values are used with text-align property.
Margins: In CSS margin area specifies the area around the border area.
Borders: In CSS Border area specifies the area around the padding area
Padding: In CSS padding area specifies the area around the content area.
Content: In CSS content area specifies the displays the content of a document, such as text and
images. This is bounded by a rectangle, which is called the content edge.
Note Content area always appears inside the padding area.
A CSS box model is a compartment that includes numerous assets, such as edge, border, padding,
and material. It is used to develop the design and structure of a web page. It can be used as a set of
tools to mark the layout of different components. According to the CSS box model, the web browser
supplies each element as a square prism.
The various other features of the box model are in the following sections:
Web Technologies
Example,
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
In order to set the width and height of an element correctly in all browsers, you need to know
how the box model works.
Important: When you set the width and height properties of an element with CSS, you just set
the width and height of the content area. To calculate the full size of an element, you must also
add padding, borders, and margins.
Example:
• This <div> element will have a total width of 350px:
div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
How to calculate:
320px (width)
1. background-color
2. background-image
3. background-repeat
4. background-attachment
5. background-position
The background-colorproperty is used to set the color of the background area on which an element
is displayed. It can be applied to any element. The background color property takes any of the
following three values.
Color name
Hexadecimal equivalence of the color
RGB color
Example,
h1
{ background-color:# FFFFFF;}
Example,
Body
{background-image: url(abc.jpg”)
Web Technologies
The background-repeatpropertyallows you to piece the background images along the x-axis and y-
axis of an element. The background-repeat property can take either of the following values:
Repeat-x
Repeat-y
Repeat
No-repeat
Example,
{
<body style=”background: url(‘abc.jpg’); background-repeat:repeat-y,”>
The background-attachmentproperty is used to fix or scroll the background image along with the
text and other content displayed on it. The two values take this property fixed or scroll. Fixed
means the background image does not move and scroll means the image scroll along with the text
written over it.
Example,
{
Body {background-image:url(‘abc.jpg’); background -attachement:scroll;}
}
Example,
{
Body {background-image:url(‘abc.jpg’); background -position: right top;}
}
The opacity property is often used together with the: hover selector to change the opacity on
mouse-over.
The float property is used for positioning and formatting content e.g. let an image float left to
the text in a container.
The float property can have one of the following values:
left - The element floats to the left of its container
right - The element floats to the right of its container
None - The element does not float (will be displayed just where it occurs in the text). This is
default
Inherit - The element inherits the float value of its parent.
Note: In its simplest use, the float property can be used to wrap text around images.
Web Technologies
float: left;
}
Example of No float
In the following example the image will be displayed just where it occurs in the text
(float: none ;):
Normally div elements will be displayed on top of each other. However, if we use
float: left we can let elements float next to each other.
When we use the float property, and we want the next element below (not on right or left), we
will have to use the clear property.
The clear property specifies what should happen with the element that is next to a floating
element
Clear property can have one of the following values:
None - The element is not pushed below left or right floated elements. This is default
left - The element is pushed below left floated elements
right - The element is pushed below right floated elements
both - The element is pushed below both left and right floated elements
inherit - The element inherits the clear value from its parent
When clearing floats, you should match the clear to the float: If an element is floated to the
left, then you should clear to the left. Your floated element will continue to float, but the
cleared element will appear below it on the web page.
Example,
This example clears the float to the left. Here, it means that the <div2> element is pushed
below the left floated <div1> element:
div1
{
float: left;
}
div2
{
clear: left;
}
The Clearfix Hack
If a floated element is taller than the containing element, it will "overflow" outside of its
container. We can then add a clearfix hack to solve this problem:
Relative Positioning
Relative Positioning changes the position of the HTML element relative to where it normally
appears. So “left30” 30 pixels to the element LEFT position.
You can use two values top and left along with the position property to move an HTML element
anywhere in the HTML document.
Move left
Move right
Web Technologies
Move top
Move bottom
<html>
<head>
</head>
<body>
<div style = “position:relative; left 50px; top:3px; background-color red”>
This is a CSS3 document.
</div>
</body>
</html>
Note:You can use bottom or right values as well in the same way as top and left.
Absolute Positioning
An element with position: absolute is positioned at the specified coordinates relative to your screen
top-left
corner.
You can use two values top and left along with the position property to move an HTML element
anywhere in the HTML document.
Move left
Move right
Move top
Move bottom
<html>
<head>
</head>
<body>
<div style = “position:relative; left 50px; top:3px; background-color red”>
This is a CSS3 document.
</div>
</body>
</html>
Summary
Font’s properties help the person who reads to easily understand and identify important
terms and information in a document.
Box model is used when talking about design and layout. The CSS box model is essentially a
box that wraps around every HTML element.
Background properties at the same place in a style sheet, can be used to specify the values for
the background color, background image, background-repeat, background-attachment,
background position, and background-size properties.
The opacity property is used to produce a transparency effect in an HTML element.
Internet browser does not support the opacity property.
Css3 enables to set ofa gradient background for an element. Gradient background is a
variation of colors,which are arranged from lightest to darkest or vice versa.
Background color property can take the value in three ways: as the direct color name, in
hexadecimal color format, or in RGB color format.
Color properties in CSS enables you to add different types of colors to our web page using the
different specification. these specifications are RGB,RGBA,HSL,HSLA and opacity.
Positioning allows you to take elements out of normal document flow and make them behave
differently.
Absolute values are the fixed value that is used to specify the font size on a web page.
Relative value is how to set the font size of the text using relative values.
Keywords
Font sizeis used to change the size of the text.
Absolute Value Refers to the absolute size of the font.
Font-style property is used to specify the style of the font.
Text-align sets the horizontal alignment of the text.
Padding property is set the values for all four directions in a box layout model.
Border is specified between the padding and content in the box model.
URL () value allows you to provide the file path to any image, and it will show the background for
that element
Self Assessment
A. height
B. padding-height
C. top
D. padding-top
2.A CSS _________is a compartment that includes numerous assets, such as edge, border,
A. box model
B. table
C. Bootstrap
D. None of these
3.Which of the following property defines the style for the bottom border of an element?
A. border-bottom-style
B. border-collapse
C. border-style-bottom
D. none of the mentioned
4.Which of the following property defines the style for the Top border of an element?
A. border-top -style
Web Technologies
B. border-collapse
C. border-style-top
D. none of the mentioned
5. Which of the following property defines the style for the Right border of an element?
A. border-right-style
B. border-left -style
C. Margin-right
D. none of the mentioned
6. Which of the following property defines the style for the left border of an element?
A. border-right-style
B. border-left -style
C. Margin-left
D. none of the mentioned
A. Padding
B. Border
C. Margin
D. None of these
A. Padding
B. Border
C. Margin
D. None of these
A. Padding
B. Border
C. Margin
D. None of these
10.Which of the following visibility property value is described by The element is not visible,
A. visible
B. hidden
C. collapse
D. none of the mentioned
11. Which of the following property is used to control the behavior of floating elements?
A. format
B. clean
C. clear
D. remove
12. The ______ property is used for positioning and formatting content
A. Float
B. clean
C. clear
D. remove
13. The CSS______ property specifies what elements can float beside the cleared element and on
which side
A. format
B. clean
C. clear
D. remove
15. Which float property ensures the element floats to the right of its container
A. None
B. Right
C. Left
D. Top
l. D 2. A 3. A 4. A 5. A
6. B 7. A 8. B 9. B 10. C
Review Questions
1. How do assign absolute values using the font-size property?
2. Explain font-size property using percentage values?
Web Technologies
3. What is the main property of the Box Model in CSS Explain with an example?
4. What are the two properties that influence the dimensions of the content in the CSS Box
Model?
5. Tell us about the property used for image scroll controlling
6. How to use the margin property of a box Explain with an example?
7. How to set the top margin property of an element? Negative values can be allowed in this
property?
8. Display a margin of 10cm from the right and 10 am from the top?
9. Tell us about column-span and column fill properties?
Further Readings
HTML5BlackBook(CoversCSS3,JavaScript,XML,XHTML,AJAX,PHP,jQuery)2Ed.
WebEnabledCommercialApplicationDevelopmentUsingHTML,JavaScript,DHTMLa
ndPHP(4thRevisedEdition)
Trevor Burnham. Async JavaScript. The Pragmatic Bookshelf, Raleigh, NC and
Dallas, TX, 2012.
Objectives
After studying this unit, you will be able to:
Introduction
The most popular HTML, CSS, and JavaScript framework for creating responsive and mobile-
friendly websites is called Bootstrap. Utilization and download are both completely free. It is a
front-end framework used to make web development simpler and quicker. It offers design
templates for typography, forms, buttons, tables, navigation, modals, image carousels, and many
other things that are based on HTML and CSS.
Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables,
navigation, modals, image carousels and many other, as well as optional JavaScript plugins.
Example: Bootstrap is a free front-end framework for faster and easier web development. It
also give you the ability to easily create responsive designs.
Bootstrap 3, framework consists of Mobile first styles throughout the entire library instead them of
in separate files.
Browser Support
It is supported by all popular browsers.
Easy to Get Started
With just the knowledge of HTML and CSS, anyone can get started with Bootstrap. Also, the
Bootstrap official site has good documentation.
Responsive design
Bootstrap's responsive CSS adjusts to Desktops, Tablets and Mobiles. More about the responsive
design is in the chapter Bootstrap Responsive Design. Provides a clean and uniform solution for
building an interface for developers.It contains beautiful and functional built-in components which
are easy to customize.It also provides web-based customization.And best of all it is open-source.
• As a result, it will be loaded from cache when they visit your site, which leads to faster
loading time.
• Also, most CDN's will make sure that once a user requests a file from it, it will be served
from the server closest to them, which also leads to faster loading time.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
</html>
Bootstrap is mobile-first
To ensure proper rendering and touch zooming, add the following <meta> tag inside
the <head> element:
<meta name="viewport" content="width=device-width, initial-scale=1">
Bootstrap is mobile-first
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.
Containers
Bootstrap 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.
Example: Containers are not nestable (you cannot put a container inside another
container).
Bootstrap Grids
Bootstrap’s grid system allows up to 12 columns across the page.
If you do not want to use all 12 columns individually, you can group the columns together to create
wider columns:
<div class="col-md-12">Span 12 columns</div>
<div class="col-md-6">Span 6</div><div class="col-md-6">Span 6</div>
<div class="col-md-4">Span 4</div><div class="col-md-8">Span 8</div>
<div class="col-md-4">Span 4</div><div class="col-md-4">Span 4</div><div class="col-md-
4">Span 4</div>
Bootstrap's grid system is responsive, and the columns will re-arrange automatically depending on
the screen size.
Grid Classes
The Bootstrap grid system has four classes:
xs (for phones)
sm (for tablets)
md (for desktops)
lg (for larger desktops)
The classes above can be combined to create more dynamic and flexible layouts.
<!DOCTYPE html>
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Any title</title>
</head>
<body>
//write code
</body>
</html>
Add the HTML 5 doctype:
Bootstrap uses HTML elements and CSS properties, so you have to add the HTML 5 doctype at the
beginning of the page with lang attribute and correct character set.
• Bootstrap 3 is designed to be responsive to mobile devices.
• Mobile-first styles are part of the core framework of Bootstrap. You have to add the
following <meta> tag inside the <head> element for proper rendering and touch zooming:
Note: The "width=device-width" part is used to set the width of the page to follow the screen-
width of the device (vary according to the devices).
The initial-scale=1 part is used to set the initial zoom level when the page is first loaded by the
browser.
The "width=device-width" part is used to set the width of the page to follow the screen-width of the
device (vary according to the devices).The initial-scale=1 part is used to set the initial zoom level
when the page is first loaded by the browser.
Creating a standard navigation bar at the top of the page with with:
<NAV CLASS="NAVBAR NAVBAR-DEFAULT">.
Background Colors
The classes for background colors are
• bg-primary,
• .bg-success,
• .bg-info, .bg-warning,
• .bg-danger,
• .bg-secondary,
• .bg-dark and
• .bg-light.
Add class .form-control to all textual <input>, <textarea>, and <select> elements
Horizontal form
Additional rules for a horizontal form:
Add class. form-horizontal to the <form> element
Add class. control-label to all <label> elements
Tip: Use Bootstrap's predefined grid classes to align labels and groups of form controls in a
horizontal layout.
The numbers (5, 10, and 2) are the badges.Use the .badge class within <span> elements to create
badges:Badges can also be used inside other elements, such as buttons:
Labels
Labels are used to provide additional information about something:
Use the. label class, followed by one of the six contextual classes. label-default,. label-primary,.
label-success, .label-info, .label-warning or .label-danger, within a <span> element to create a label:
Indicators
The .carousel-indicators is the class that can be used to add indicators for the carousel. The
indicators in this class are used to indicate how many slides are in the carousel, and which slide the
user is currently viewing.
Captions
A user can also add captions to their slides in Bootstrap 4. A caption can be easily used to convey to
the audience of the website that what exactly is happening in the carousel. For the purpose of
adding captions, a user has to add elements inside <div class="carousel-caption"> within each <div
class="carousel-item"> in order to create a caption for every slide.
Creating a model
<!-- The Modal -->
Grid
Furthermore, Bootstrap provides a grid system, which creates a page layout through a series of
rows and columns that can place the content. There is no Grid system in CSS.
Designing Classes
Also, Bootstrap contains already designed classes. The programmer can use them in his program to
add styling to the elements without writing code from the beginning. On the other hand, in CSS,
the programmer should write the code from scratch.
Considering the usage, the Bootstrap helps to create responsive designs that are more presentable
while CSS helps to create presentable webpages. Bootstrap and CSS help to build presentable user
interfaces. The basic difference between Bootstrap and CSS is that the Bootstrap is a front-end
framework while CSS is a style sheet language. They help to add background and borders, text
effects, 2D, 3D animations etc. to web pages.
</div>
Summary
Bootstrap is a free front-end framework for faster and easier web development. It also gives
you the ability to easily create responsive designs.
Content delivery network (CDN) is a system of distributed servers (network) that deliver
webpages and other Web content to a user based on the geographic locations of the user, the
origin of the webpage and a content delivery server.
A caption can be easily used to convey to the audience of the website that what exactly is
happening in the carousel
Bootstrap provides a grid system, which creates a page layout through a series of rows and
columns that can place the content. There is no Grid system in CSS.
Bootstrap's global default font-size is 14px, with a line-height of 1.428.This is applied to the
<body> element and all paragraphs (<p>).
Bootstrap 3 is designed to be responsive to mobile devices.Mobile-first styles are part of the
core framework of Bootstrap.You have to add the following <meta> tag inside the <head>
element for proper rendering and touch zooming:
Keywords
Bootstrap: Bootstrap is a free front-end framework for faster and easier web development. It also
give you the ability to easily create responsive designs.
Carousel -A carousel in Bootstrap 4 can be defined as a slideshow that is used for the purpose to
slideshow through a series of content to show the audience the content and to enhance the website
CSS- Bootstrap comes with the feature of global CSS settings, fundamental HTML elements styled
and enhanced with extensible classes, and an advanced grid system
Grids- Bootstrap provides a grid system, which creates a page layout through a series of rows and
columns that can place the content.
Containers- Containers are not nestable (you cannot put a container inside another container).
Bootstrap Inline: In an inline form, all of the elements are inline, left-aligned, and the labels are
alongside
Navigation Bar- A navigation bar is like a navigation header that is placed at the top of the page.
You can collapse or extend it according to the screen size
Inverted Navigation Bar: Inverted navigation bar provides an alternative black navbar. It can be
used to style the default navigation bar by changing. navbar-default class into. navbar-inverse
class.
Self Assessment
1. Which of the following class in Bootstrap is used to provide a responsive fixed width
container?
A. .container-fixed
B. .container-fluid
C. .container
D. All of the above
2. Is Bootstrap3 mobile-first?
A. True
B. False
C. Can't say
D. May be
6. Which of the following class in bootstrap is used to create a big box for calling extra
attention?
A. .box
B. .container
C. .container-fluid
D. .jumbotron
D. Lg
11. Which class in Bootstrap Grid System used for larger desktops:
A. Xs
B. Sm
C. Md
D. Lg
A. Labels
B. Badges
C. Headings
D. None of these
A. Carousel
B. Labels
C. Badges
D. Headings
6. D 7. B 8. A 9. B 10. C
Review Questions
1. Explain why Bootstrap is preferred for website development?
2. What is Bootstrap Grid System? Explain with an example?
3. Explain the typography and links in Bootstrap
4. What is media object in Bootstrap and what are their types
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross.
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, PhpAndJquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction to JavaScript
Introduction
A lightweight programming language ("scripting language")used to make web pages
interactiveinsert dynamic text into HTML (ex: user name), react to events (ex: page load user click),
get information about a user's computer (ex: browser type), perform calculations on user's
computer (ex: form validation).
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in Netscape
2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded
in Netscape, Internet Explorer, and other web browsers.
Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly.
Adding and deleting any HTML tag very easily using javascript and modify your HTML
to change its look and feel based on different devices and requirements.
User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to
give different types of notifications to your website visitors
Web Technologies
Back-end Data Loading - Javascript provides Ajax library which helps in loading back-
end data while you are doing some other processing. This really gives an amazing
experience to your website visitors.
Presentations - JavaScript also provides the facility of creating presentations which gives
website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-
based slide presentations.
Client Side validation - This is really important to verify any user input before submitting
it to the server and Javascript plays an important role in validting those inputs at front-end
itself.
Example:To "make web pages alive," JavaScript was initially developed. Scripts are what
the programmes in this language are known as. They can be directly written in the HTML
of a web page and executed when the page loads. Plain text scripts are delivered and run.
They can run without any additional setup or compilation.
Event-driven Programming
Split breaks apart a string into an array using a delimiter. It can also be used with regular
expressions (seen later). Join merges an array into a single string, placing a delimiter between them
Angular
React
jQuery
Vue.js
Ext.js
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.You can place the <script> tags, containing your JavaScript,
anywhere within your web page, but it is normally recommended that you should keep it within
the <head> tags. The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script
JavaScript syntax
A simple syntax of your JavaScript will appear as follows.
Web Technologies
<script ...>
JavaScript code
</script>
Script tag
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using. Typically, its
value will be javaScript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to "text/javaScript".
Script Tag
<script language = "javaScript" type = "text/javaScript">
JavaScript code
</script>
First JavaScript Code
Let us take a sample example to print out "Hello World“
. <html>
<body>
<script language = "javascript" type = "text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Browser
You can also install the following browser as per your preference:
Microsoft Edge
Google Chrome
Mozilla FireFox
Safari
Opera
IDEs for JavaScript Application Development
You can write JavaScript code using a simple editor like Notepad. However, you can install any
open-sourced or licensed IDE (Integrated Development Environment) to get the advantage of
IntelliSense support for JavaScript and syntax error/warning highlighter for rapid development.
JavaScript Editors:
The followings are some of the well-known JavaScript editors:
• Visual Studio Code (Free, cross-platform)
• Eclipse (Free, cross-platform)
• Atom (Free, cross-platform)
• Notepad++ (Free, Windows)
• Code Lobster (Free, cross-platform)
• WebStorm (Paid, cross-platform)
Web Technologies
• The example below "finds" an HTML element (with id="demo"), and changes the element
content (innerHTML) to "Hello JavaScript":
• Example
• document.getElementById("demo").innerHTML = "Hello JavaScript";
JavaScript Can Change HTML
Attribute Values
JavaScript changes the value of the src (source) attribute of an <img> tag
JavaScript changes the value of the src (source) attribute of an <img> tag
• Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
• In following example (next slide), a JavaScript function is placed in the <head> section of
an HTML page.
• The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body><h2>Demo JavaScript in Head</h2>
JavaScript in <body>
• In this example(next slide), a JavaScript function is placed in the <body> section of an
HTML page.
• The function is invoked (called) when a button is clicked:
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Example:
<script src="myScript.js"></script>
You can place an external script reference in <head> or <body> as you like.The script will behave
as if it was located exactly where the <script> tag is located.
Web Technologies
JavaScript Output
• JavaScript Display Possibilities
• JavaScript can "display" data in different ways:
– Writing into an HTML element, using innerHTML.
– Writing into the HTML output using document.write().
– Writing into an alert box, using window.alert().
– Writing into the browser console, using console.log().
Using innerHTML
• To access an HTML element, JavaScript can use the document.getElementById(id)
method.
• The id attribute defines the HTML element. The innerHTML property defines the HTML
content
Using document.write()
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using window.alert()
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
JavaScript Comments
• JavaScript comments can be used to explain JavaScript code, and to make it more readable.
• JavaScript comments can also be used to prevent execution, when testing alternative code.
Multi-line Comments
• Multi-line comments start with /* and end with */.
• Any text between /* and */ will be ignored by JavaScript.
Summary
A lightweight programming language ("scripting language")used to make web pages
interactiveinsert dynamic text into HTML.
Scripts are what the programme ‘s in this language are known as. They can be directly written
in the HTML of a web page and executed when the page loads.
A JavaScript function is a block of JavaScript code, that can be executed when "called" for
Placing scripts in external files has some advantages: It separates HTML and code
Split breaks apart a string into an array using a delimiter. It can also be used with regular
expressions (seen later). Join merges an array into a single string, placing a delimiter between
them
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
External scripts are practical when the same code is used in many different web
pages.JavaScript files have the file extension .js.
One of many JavaScript HTML methods is getElementById().
Keywords
Javascript: Bootstrap is a free front-end framework for faster and easier web development. It also
give you the ability to easily create responsive designs.
JavaScript Developer- To use JavaScript in developing a web application you must have at least
two things, a browser, and an editor to write the JavaScript code.
External scripts- The are practical when the same code is used in many different web
pages.JavaScript files have the file extension .js.
Inner HTML- To access an HTML element, JavaScript can use the document.getElementById(id)
method.
JavaScript Function-A JavaScript function is a block of JavaScript code, that can be executed when
"called" for
IDEs for JavaScript- JavaScript code using a simple editor like Notepad. However, you can install
any open-sourced or licensed IDE (Integrated Development Environment)
Self Assessment
Web Technologies
D. None of above
2. It is a technique used in web development in which scripts run on the client's browser
A. client-side scripting
B. Server side
C. Both of above
D. None of above
3. It is a technique that uses scripts on the webserver to produce a response that is customized
for each client's request.
A. client-side scripting
B. Server side Scripting
C. Both of above
D. None of above
9. JavaScript ignores?
A. newlines
B. tabs
C. spaces
D. All of the above
11. Which property is used to define the HTML content to an HTML element with a specific id?
A. innerText
B. innerContent
C. elementText
D. innerHTML
14. How many keywords are there in JavaScript to declare variables or constants?
A. 1
B. 2
C. 3
D. 4
15.What is the main difference between var and let keywords in JavaScript?
A. var defines a variable while let defines a constant
B. var defined function scoped variable while let define block scoped variable
C. The value of a variable declared with var can be changed while the value of a variable
declared with let cannot be changed
D. All of the above
6. A 7. B 8. D 9. D 10. C
Review Questions
1. Explain JavaScript? Explain its application in HTMl?
Web Technologies
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross.
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, PhpAndJquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Aseem Khanna, Lovely Professional University Unit 08: Variables and Functions
Objectives
After studying this unit, you will be able to:
Introduction
To workwith JavaScript as other programming languages, JavaScript has variables for the storage
of some value. Variables can be assumed of as named containers. You can place data into these
containers and then refer to the data simply by naming the container.
Before we use a variable in a JavaScript program, it must be declared with the var keyword as
follows.
<script type = "text/javascript">
<!--
var price;
var name;
//-->
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var price,name;
//-->
</script>
Storingor placing a value in a variable is called variable initialization.Variable initialization at the
time of variable creation or when you need that variable.
For instance, we might create a variable named price and assign the value 2000 to it later. For
another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "hardisk";
var price;
price = 2000;
//-->
</script>
Example: The var keyword is used only for declaration or initialization, only once variable
name is declared, and variable name cannot be same in document.
JavaScript is an untyped language which means JavaScript variable can hold a value of any data
type. Unlike many other languages, you don't need to tell JavaScript during variable declaration
what type of value the variable will hold. The value type of a variable can change during the
execution of a program and JavaScript takes care of it automatically.
<html>
<body onload = vscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function vscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
This produces the following result −
local
JavaScript Variable Names
While naming our variables in JavaScript, following rules must be kept in mind.
wemust not use any typeof JavaScript reserved keywords as a variable name. These keywords are
mentioned in the table below. For example, break or boolean variable names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or an
underscore character. For example, 12test is an invalid variable name but _12test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.
JavaScript Reserved Words
double in super
<head>
<scripttype="text/javasc
ript">function test()
{
document.write("Hello World!");
}
</script>
</head>
<body>
<p>Clicktocallthefunction</p>
<form>
<inputtype="button"onclick="test()"value="Hello World">
</form>
Output:
Clicktocallthefunction
Hello World
For example we have modified our test function here. Now it takes two parameters.
<html>
<head>
<scripttype="text/javascript">fu
nctiontest(name,age)
{
document.write(name+"is"+age+"yearsold.");
</script>
</head>
<body>
<p>Clicktocallthefunction</p>
<form>
<inputtype="button"onclick="test('Aseem',7)"value="Hello world">
</form>
<p>Usedifferentparametersinsidethefunctionandthentry...</p>
</body>
</html>
Output
HELLO WORLD
<html>
<head>
<script
type="text/javascript">functioncon
catenate(first,last)
varfull;
full=first+last;re
turnfull;
}
functionsecondFunction()
varresult;
result=concatenate('Zara','Ali');document.write(re
sult);
</script>
</head>
<body>
<p>Clickthefollowingbuttontocallthefunction</p>
<form>
<inputtype="button"onclick="secondFunction()"value="CallFunction">
</form>
<p>Usedifferentparametersinsidethefunctionandthentry...</p>
</body>
</html>
Call Function
function printValue(a=2, b) {
console.log("a = " + a + " and b = " + b);
The above, when we provided no argument while calling the function then, a used its default value
while b got undefined. So provided one argument while calling the function, and that argument got
assigned to the first parameter which is a, as argument assignment to parameters happens in order,
hence b again got undefined.
Default values for parameters and calling it without arguments are explained in below example.
Output
Sum is : 30
Sum is : 21
Sum is : 11
Summary
JavaScript supports a number of types of data, Such as numbers, text, and Booleans.
Variables are JavaScripts’s way of storing data, such as numbers and text, in memory so that
they can be used again and again in your code.
Variable names must not include certain illegal characters, like % and &, or be reserved word,
like with.
Use a function keyword to declare a function.
FunctionName() is used to call a function.
All functions implicitly return undefined if they don’t explicitly return a value.
the return statement to return a value from a function explicitly can be used.
The arguments variable is an array-like object inside a function, representing function
arguments.
The function hoisting allows you to call a function before declaring it.
Keywords
Variables: Variables can be assumed as named containers. You can place data into these containers
and then refer to the data simply by naming the container.
Functions: A function is a set of reusable codesthat may be called anywhere in your program. This
removes the need of writing the identical code multiple times.
JavaScript Datatype: JavaScript is a dynamic type language; means there is no need to specify type
of the variable because it is dynamically used by JavaScript engine.
Number: Number variables are just that—numbers. JavaScript does not require numbers to be
declared as integers, floating-point (decimal) numbers, or any other number type.
Strings:String variables are variables that represent a string of text. The string may contain letters,
words, spaces, numbers, symbols, or most anything you like
Parameters:Parameters are used to allow a function to import one or more values from somewhere
outside the function
Global Variables:They are defined outside any functions; they can be changed anywhere in the
script—inside or outside of functions
Local Variables:A local variable can be used only within the function in which it is declared. It does
not exist outside that function, unless you pass it along to another function by using a parameter.
Self Assessment
12. In JavaScript a variable contains one value while an object may contain ___.
A. One value
B. Two values
C. Three values
D. Many values
15. Which character is used to break up a code line within a text string in JavaScript?
A. Single quote (')
B. Single backslash (\)
C. Double quote (")
6. A 7. D 8. B 9. A 10. D
Review Questions
1. Write a JavaScript code block using arrays and generate the current date in words, this
should include the day, the month and the year. The output should be as follows,
Saturday, October 09,2021.
2. What if I put a function into my script but decide not to call it in the script? Will it matter?
3. What happens if I decide to remove a function from my script later?
4. What is the best way to determine when to use a function and when to just code what I
want right into the script?
5. Write a JavaScript function which accepts an argument and returns the type
Note : There are six possible values that typeof returns: object, boolean, function, number,
string, and undefined.
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross.
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, Php And Jquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
JavaScript is an Object-Oriented Programming (OOP) language In JavaScript, an object is a
standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object,
with properties. A cup has a color, a design, weight, a material it is made of, etc. In the same way,
JavaScript objects can have properties, which define their characteristics. As a programming
language it must provide the following features to become anObject-Oriented Language:
Encapsulation: the capability to store related information, whether data or methods, together in an
object.
Aggregation: the capability to store one object inside another object.
Inheritance: the capability of a class to rely upon another class (or the number of classes) for some
of its properties and methods.
Polymorphism: the capability to write one function or method that works in a variety of different
ways.
Objects are composed of attributes. If an attribute contains a function, it isconsidered to be a
method of the object, otherwise, the attribute is considered aproperty
In JavaScript, objects are king. If you understand objects, you understand JavaScript. In JavaScript,
almost "everything" is an object. Booleans can be objects (if defined with the new keyword),
Web Technologies
Numbers can be objects (if defined with the new keyword), Strings can be objects (if defined with
the new keyword), Dates are always objects, Maths are always objects, Regular expressions are
always objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods and a primitive data type is a data
that has a primitive value.
JavaScript defines 5 types of primitive data types:
string
number
boolean
null
undefined
Primitive values are immutable (they are hardcoded and therefore cannot be changed). For e.g. If x
= 3.14, you can change the value of x. But you cannot change the value of 3.14.
Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data types,
such as another object. Object properties are typically variables that are used internally in the
object's methods but can also be globally visible variables that are used throughout the page.
objectName.objectProperty=propertyValue;
This code gets the document title using the "title" property of the document object.
varstr=document.title;
Objects written as name value pairs are similar to:
Object Method
Methods are actions that can be performed on objects. Object properties can be both primitive
values, other objects, and functions. An object method is an object property containing a function
definition.
There is a small difference between a function and a method – at a function is a standalone unit of
statements and a method is attached to an object and can be referenced by the this keyword
Methods are useful for everything from displaying the contents of the object to the screen to
performing complex mathematical operations on a group of local properties and parameters.
For example: The following is a simple example to show how to use the
write() method of the document object to write any content on the document.
document.write("Hello World");
Web Technologies
<scripttype="text/javascript">
varmyclass=new class("BCA","Ashraf");myclass.addtest(sst);
document.write("Student Name is : " + myclass.sname +
"<br>");document.write("Student
Courseis:"+myclass.course+"<br>");document.write("Student test
courseis:"+myclass.test+"<br>");
</script>
</body>
</html>
OUTPUT:
Student Name is: Aseem Khanna
Student Course is:BCA
Student Test Course is: DBMS
Syntax
with(object){
propertiesusedwithouttheobjectnameanddot
}
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Definition of a function which will work as a method function addPrice(amount){
with(this){
price = amount;
}
}
function Car(model, manufacturer)
{
this.model = model;
this.manufacturer = manufacturer;.this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var mycar = new car("Thar", "Mahindra"); mycar.addPrice(1200000);
document.write("Car model is : " + mycar.model + "<br>");
document.write("Car Manufacturer is : " + mycar.manufacturer + "<br>");
document.write("Car Price is : " + mycar.price + "<br>");
</script>
</body>
</html>
Output:
Car modelis:Thar
Car Manufactureris: Mahindra
Car Price is: 1200000
Web Technologies
Web Technologies
</html>
Output:
Entering switch block good job
Exiting switch block
Set the variable to different value and then try...
JavaScript For Of
The JavaScript for of statement loops through the values of an iterable object. It lets you loop over
iterable data structures such as Arrays, Strings, Maps, NodeLists, and more
for (variable of iterable)
{
// code block to be executed
}
Example Explanation
• variable - For every iteration the value of the next property is assigned to the variable.
Variable can be declared with const, let, or var.
• iterable - An object that has iterable properties.
Web Technologies
Method Description
new
Creates a new Set
Set()
Example
// Create a Set
const letters = new Set(["a","b","c"]);
// code to be executed
}
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are invoked (called upon).
Example
function myFunction(a, b)
{
return a * b;
}
Semicolons are used to separate executable JavaScript statements.Since a function declaration is not
an executable statement, it is not common to end it with a semicolon.
Example
const x = function (a, b) {return a * b};
After a function expression has been stored in a variable, the variable can be used as a function
‘This’ Keyword
In an object method, this refers to the object. Alone, this refers to the global object. In a function, this
refers to the global object. In a function, in strict mode, this is undefined. In an event, this refers to
the element that received the event. Methods like call(), apply(), and bind() can refer this to any
object. Method can be reuse. With the call() method, you can write a method that can be used on
different objects. In JavaScript all functions are object methods. If a function is not a method of a
JavaScript object, it is a function of the global object
The example below creates an object with 3 properties, firstName, lastName, fullName.
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function ()
{
return this.firstName + " " + this.lastName;
}
}
// This will return "John Doe":
myObject.fullName();
Web Technologies
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18)
{
greeting = "Good day";
}
else
{
greeting = "Good evening";
}
The result of greeting will be:
Good day
Web Technologies
Summary
Objects are composed of attributes. If an attribute contains a function, it isconsidered to be a
method of the object, otherwise, the attribute is considered aproperty
Methods are actions that can be performed on objects. Object properties can be both primitive
values, other objects, and functions.
A constructor is a function that creates and initializes an object. JavaScript offers a special
constructor function called Object( ).
‘with’ Keyword represents as shorthand for referencing an Objects properties or methods.
Loops can execute a block of code as long as a specified condition is true.
A JavaScript Set is a collection of unique values. Each value can only occur once in a Set
The JavaScript for of statement loops through the values of an iterable object. It lets you loop
over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more
Keywords
Object: Objects are composed of attributes. If an attribute contains a function.
Object properties: They can be any of the three primitive data types, or any of the abstract data
types, such as another object.
Else IF: Use the else if statement to specify a new condition if the first condition is false.
JavaScript: The call() method is a predefined JavaScript method.It can be used to invoke (call) a
method with an owner object as an argument (parameter).
Function() Constructor: JavaScript functions are defined with the function keyword.Functions can
also be defined with a built-in JavaScript function constructor called Function().
JavaScript Set: A JavaScript Set is a collection of unique values. Each value can only occur once in a
Set.
‘This’ Keyword: this refers to the global object. In a function, this refers to the global object. In a
function, in strict mode, this is undefined. In an event, this refers to the element that received the
event.
Self Assessment
A. Object
B. Arrays
C. Output
D. Input
6. Because the ________ loop checks the condition/expression before the block is executed, the
control structure is often also known as a pre-test loop
A. While loop
B. Not While loop
C. Do While loop
D. All of the above
7. Because ______loops check the condition after the block is executed, the control structure is
often also known as a post-test loop
A. While loop
B. Not While loop
C. Do While loop
D. All of the above
Web Technologies
C. set
D. array
12. Use the _______statement to specify a new condition if the first condition is false.
A. else if
B. else
C. if
D. all of the above
14. Find output of below JavaScript addition codedocument.write ("1 plus 1 is " + 1 + 1);
A. 2
B. 1 plus 1 is 2
C. 1 plus 1 is 11
D. 1 plus 1 is 1 + 1
6. A 7. C 8. A 9. B 10. A
Review Questions
1. Display current date, Month, year and day of the week of the Machine.
2. Display current day of week(using ifelse() condition) to print “Hello Everyone Today is
Friday, Starting of a weekend”
3. Write a JavaScript program that accept two integers and display the larger.
4. Write a JavaScript conditional statement to find the largest of five numbers. Display an alert
box to show the result
5. Write a JavaScript program to find the armstrong numbers of 3 digits?
Note: An Armstrong number of three digits is an integer such that the sum of the cubes of its
digits is equal to the number itself. For example, 371 is an Armstrong number since 3**3 +
7**3 + 1**3 = 371.
6. Write a JavaScript program to compute the greatest common divisor (GCD) of two positive
integers.
7. Using a for loop output the elements in reverse order.
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross .
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, PhpAndJquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
A Document object represents the whole HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.
When html document is loaded in the browser, it becomes a document object. It is the root element
that represents the html document. It has properties and methods. By the help of document object,
we can add dynamic content to our web page.
HTML is used to structure the web pages and Javascript is used to add behavior to our web pages.
When an HTML file is loaded into the browser, the Javascript cannot understand the HTML
document directly.
Window object: Top of the hierarchy. It is the outmost element of the object hierarchy.
Document object: Each HTML document that gets loaded into a window becomes a document
object. The document contains the contents of the page.
Form object: Everything enclosed in the <form>...</form> tags sets the form object.
Form control elements: The form object contains all the elements defined for that object such as text
fields, buttons, radio buttons, and checkboxes.
Notes: DOM isn’t exclusive to JavaScript and web browsers - there are DOM parsers for
pretty much every language under the sun.
Properties of DOM
Window Object: Window Object is always at top of the hierarchy.
Document Object: When an HTML document is loaded into a window, it becomes a document
object.
Form Object: It is represented by form tags.
Link Object: It is represented by link tags.
Anchor Object: It is represented by a HREF tags.
Form Control Elements: Form can have many control elements such as text fields, buttons, radio
buttons, and checkboxes, etc.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute
onclick=JavaScript
HTML DOM allows JavaScript to react to HTML events:
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute
onclick=JavaScript
Morning")
}
//-->
</script>
</head>
<body>
<p> Click on Button to See Result</p>
<inputtype="button"onclick="ClickMe()"value="Click ME"/>
</body>
</html>
Output:
Click ME
Output:
Bringyourmouseinsidethe required area:
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keydown & Keyup Onkeydown & When the user press and then release the key
onkeyup
change onchange When the user modifies or changes the value of a form
element
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
JavaScript Cookies
A cookie is an amount of information that persists between a server-side and a client-side. A web
browser stores this information at the time of browsing. A cookie contains the information as a
string generally in the form of a name-value pair separated by semi-colons. It maintains the state of
a user and remembers the user's information among all the web pages.
When a user sends a request to the server, then each of that request is treated as a new request sent
by the different user. So, to recognize the old user, we need to add the cookie with the response
from the server. Browser at the client-side. Now, whenever a user sends a request to the server, the
cookie is added with that request automatically. Due to the cookie, the server recognizes the users.
Advantages of Cookies
Cookies do not require any server resources since they are stored on the client.
Cookies are easy to implement.
You can configure cookies to expire when the browser session ends (session cookies) or they
can exist for a specified length of time on the client computer (persistent cookies).
Disadvantages of Cookies
By decoupling the data interchange layer from the presentation layer, Ajax allows web pages and,
by extension, web applications, to change content dynamically without the need to reload the entire
page. In practice, modern implementations commonly utilize JSON instead of XML.
Ajax Technology
AJAX cannot work independently. It is used in combination with other technologies to create
interactive webpages.JavaScript is a Loosely typed scripting language.JavaScript function is called
when an event occurs in a page.Glue for the whole AJAX operation. It is also used with DOM and
API for accessing and manipulating structured documents. It represents the structure of XML and
HTML documents& CSS. It allows for a clear separation of the presentation style from the content
and may be changed by JavaScript
Summary
Javascript interprets DOM easily i.e javascript cannot understand the tags(<h1>H</h1>) in
HTML document but can understand object h1 in DOM.
Documents are modeled using objects and the model includes not only the structure of a
document but also the behavior of a document and the objects of which it is composed of like
tag elements with attributes in HTML.
Form can have many control elements such as text fields, buttons, radio buttons, and
checkboxes, etc.
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML
element.
The HTML DOM allows JavaScript to change the style of HTML elements.
The HTML DOM allows you to execute code when an event occurs.Events are generated by
the browser when "things happen" to HTML elements like when we click on an element it will
load the page and the required fields are changed.
A cookie contains the information as a string generally in the form of a name-value pair
separated by semi-colons.
The document.cookie property looks like a normal text string
Keywords
JavaScript:HTML is used to structure the web pages and Javascript is used to add behavior to our
web pages.
Form control elements: The form object contains all the elements defined for that object such as text
fields, buttons, radio buttons, and checkboxes.
DOM:DOM easily i.e javascript cannot understand the tags(<h1>H</h1>) in HTML document but
can understand object h1 in DOM.
Event: HTML DOM allows you to execute code when an event occurs.
onclick Event: This is the most frequently used event type which occurs when a user clicks the left
button of his mouse.
Onmouseover: onmouseover event triggers when you bring your mouse over any element and the
onmouseout triggers when you move your mouse out from that element
Cookie:A cookie is an amount of information that persists between a server-side and a client-side.
Cookie String: document.cookie property looks like a normal text string.
Ajax: Ajax (also AJAX "Asynchronous JavaScript and XML”) is a set of web development
techniques that uses various web technologies on the client-side to create asynchronous web
applications
JSON:JSON stands for JavaScript Object Notation. JSON is extremely trivial data-interchange
format for data exchange between server and client which is quick and easy to parse and generate.
Self Assessment
1. The W3C ____________is a platform and language-neutral interface that allows programs
and scripts to dynamically access and update the content, structure, and style of a
document.
3. What is the work of the form control elements in the HTML DOM?
A. User Interface elements
B. All the possible elements
C. Debugging elements
D. Collecting elements
5. The HTML DOM allows JavaScript to change the style of HTML elements.
A. True
B. False
6. ____________is the process of ensuring that user input is clean, correct, and useful.
A. Data validation
B. Data fragmentation
C. Data variability
D. Data analysis
8. Which event handler is used to initiate when the cursor of the mouse comes over the
element?
A. onclick
B. onmouseover
C. onmouseout
D. onmousedown
9. Which event handler is used to initiate when the cursor of the mouse leaves an element?
A. onclick
B. onmouseover
C. onmouseout
D. onmousedown
10. Which event handler in form events is used to initiate when the user focuses on an element?
A. onfocus
B. onsubmit
C. onblur
D. onchange
11. Which event handler in form events is used to initiate when the focus is away from a form
element?
A. onfocus
B. onsubmit
C. onblur
D. onchange
15. Which constraint validation specifies that the input element should be disabled
A. Disabled
B. pattern
C. required
D. type
16. Which constraint validation Specifies that the input field requires an element
A. Disabled
B. pattern
C. required
D. type
6. A 7. A 8. B 9. C 10. A
16. C
Review Questions
1. What’s the difference between window vs document?
2. What are the methods to get one or more elements from the DOM?
3. What is main function of DOM?
4. What is method involved in HTML DOM?
5. What are the functionalities performed by onload() and onUpload()?
6. What are HTML DOM Event?
7. What are JavaScript Cookies?
8. What is Ajax?
9. What isCookie String?
10. What are the JSON Techniques?
11. How parsing is done in JSON? Explain with Example?
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross .
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, Php And Jquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
React (also known as React.js or ReactJS) is a free and open-source front-end JavaScript library for
building user interfaces based on UI components. It is maintained by Meta (formerly Facebook) and
a community of individual developers and companies.
React can be used as a base in the development of single-page or mobile applications. However,
React is only concerned with state management and rendering that state to the DOM, so creating
React applications usually requires the use of additional libraries for routing, as well as certain
client-side functionality.
Components of React
At the heart of all React applications are components. A component is a self-contained module that
renders some output. We can write interface elements like a button or an input field as a React
component. Components what is React? 1 are compostable. A component might include one or
more other components in its output. Broadly speaking, to write React apps we write React
components that correspond to various interface elements. We then organize these components
inside higher-level components which define the structure of our application. For example, take a
form. A form might consist of many interface elements, like input fields, labels, or buttons. Each
element inside the form can be written as a React component. We'd then write a higher-level
Web Technologies
component, the form component itself. The form component would specify the structure of the
form and include each of these interface elements inside of it.
Virtual DOM
Another notable feature is the use of a virtual Document Object Model, or virtual DOM. React
creates an in-memory data-structure cache, computes the resulting differences, and then updates
the browser's displayed DOM efficiently. This process is called reconciliation. This allows the
programmer to write code as if the entire page is rendered on each change, while the React libraries
only render subcomponents that actually change.
Go to https://nodejs.org/en/
Download the latest version of NodeJS LTS with Administrator privileges.
Web Technologies
npm is the package manager for the Node JavaScript platform. It puts modules in place so that
node can find them, and manages dependency conflicts intelligently. It is extremely configurable to
support a wide variety of use cases. Most commonly, it is used to publish, discover, install, and
develop node programs.
React App
Root Component
Web Technologies
Compiled successfully!
You can now view react-cra-web-app in the browser.
Local: http://localhost:3000
On Your Network: http://192.168.56.1:3000
Note that the development build is not optimized. To create a production build, use npm run build.
Next, open the browser and enter http://localhost:3000 in the address bar and press enter. The
development web server will serve our webpage as shown below.
After creating a React application, we will notice that in Terminal, it provides quick tips or
commands that will help in executing the React application. For example :-
npm start - This command will start the development server.
npm run build - Bundles the app into static files for production.
npm test - starts the test runner.
npm run object - Removes this tool and copies build dependencies, configuration files, and
scripts into the app directory.
Gitignore
Thegitignore file tells Git which files to ignore when committing your project to the GitHub
repository. gitignore is located in the root directory of your repo. / will ignore directories with the
name. Ignored files are usually build artifacts and machine generated files that can be derived from
your repository source or should otherwise not be committed.
Package-lock.json
Package-lock.json contain exact dependency tree to be installed in /node_modules. It helps while a
team is working on private apps to ensure that they are working on the same version of
dependencies and sub-dependencies. It also maintains a history of changes done in package.json so,
that at any point of time, when required previous changes can be looked back in the package-
lock.json file.
node_modules
This folder contains all dependencies and sub-dependencies specified in package.json used by
React app. It contains more than 800 subfolders; this folder is automatically added in the .gitignore
file
Public–
This folder contains files which don’t require additional processing by web pack. The index.html
file is considered as an entry point for the web application. Here, the favicon is a header icon and
manifest.xml file contains configuration when your application is used for Android app
src –
This folder is the heart of React application as it contains JavaScript which needs to be processed by
webpack. In this folder, there is a main component App.js, its related styles (App.css), test suite
(App.test.js). index.js, and its style (index.css); which provide an entry point into the App. Lastly, it
Web Technologies
contains registerServiceWorker.js which takes care of caching and updating files for the end user. It
helps in offline capability and faster page loading after the first visit.
11.3 ES6
ES6 stands for ECMAScript 6.ECMAScript was created to standardize JavaScript, and ES6 is the 6th
version of ECMAScript, it was published in 2015, and is also known as ECMAScript
2015.ECMAScript (European Computer Manufacturers Association Script) is a scripting language
based on JavaScript. Invented by Brendan Eich at Netscape, ECMAScript made its first appearance
in the Navigator 2.0 browser.
ES6 or ECMAScript 6 is a scripting language specification which is standardized by ECMAScript
International. This specification governs some languages such as JavaScript, Action Script, and
Jscript. ECMAScript is generally used for client-side scripting, and it is also used for writing server
applications and services by using Node.js. ES6 allows you to write the code in such a way that
makes your code more modern and readable. By using ES6 features, we write less and do more, so
the term 'Write less, do more' suits ES6. ES6 introduces you many great features such as scope
variable, arrow functions, template strings, class destructions, modules, etc
Example:
A simple class constructor:
Class Car
{
Constructor (name) {
This. brand = name;
}
}
Class Car {
Constructor (name) {
This. brand = name;
}
}
Constmy car = new Car("Ford");
ES6 Arrays
An array declaration allocates sequential memory blocks and is static. This means that an array
once initialized cannot be resized. Each memory block represents an array element. Array elements
are identified by a unique integer called as the subscript/index of the element. Arrays too, like
variables, should be declared before they are used. Array initialization refers to populating the
array elements. Array element values can be updated or modified but cannot be deleted
For example, a declaration like: var numlist = [2,4,6,8] will create an array as shown in the
following figure.
Arrow Function
Arrow functions are introduced in ES6 which provides you a more accurate way to write the
functions in JavaScript. They allow us to write smaller function syntax. Arrow functions make your
Web Technologies
code more readable and structured. They are also known as anonymous functions (the functions
without a name and not bound with an identifier). They don't return any value and can declare
without the function keyword. Arrow functions cannot be used as the constructors.
Arrow functions allow us to write shorter function syntax:
Before:
Hello = function ()
{
Return "Hello World!";
}
After the use of arrow function
Hello = () =>
{
Return "Hello World!";
}
It gets shorter! If the function has only one statement, and the statement returns a value, you can
remove the brackets and the return keyword.
Arrow Functions Return Value by Default:
Hello = () => "Hello World!";
If you have parameters, you pass them inside the parentheses:
Arrow Function with Parameters:
Hello = (val) => "Hello” + val;
THIS Function
The handling of this is also different in arrow functions compared to regular functions. In short,
with arrow functions there are no binding of this. In regular functions the this keyword represented
the object that called the function, which could be the window, the document, a button or whatever.
With arrow functions, this keyword always represents the object that defined the arrow function.
Let
Let x = 5.6;
Let is the block scoped version of var, and is limited to the block (or expression) where it is defined.
If you use let inside of a block, i.e.a for loop, the variable is only available inside of that loop. let has
a block scope.
Const
Const x = 5.6;
Const is a variable that once it has been created, its value can never change.const has a block scope.
Named: Named exports are distinguished by their names. There can be several named exports
in a module. A module can export selected components using the syntax given below −
Syntax:
//using multiple export keyword
Export component1
Export component2
...
...
ExportcomponentN
Default export: Modules that need to export only a single value can use default exports. There
can be only one default export per module.
Syntax
Export default component_name
Summary
React (also known as React.js or ReactJS) is a free and open-source front-end JavaScript
library for building user interfaces based on UI components.
Virtual Document Object Model, or virtual DOM. React creates an in-memory data-structure
cache, computes the resulting differences, and then updates the browser's displayed DOM
efficiently.
ES6 or ECMAScript 6 is a scripting language specification which is standardized by
ECMAScript International.
Gitignore file tells Git which files to ignore when committing your project to the GitHub
repository.
Web Technologies
Classes are an essential part of object-oriented programming (OOP). Classes are used to define
the blueprint for real-world object modeling and organize the code into reusable and logical
parts
Keywords
React:React can be used as a base in the development of single-page or mobile applications
Const: const is a variable that once it has been created, its value can never change.const has a
block scope.
Let:let is the block scoped version of var, and is limited to the block (or expression) where it is
defined.
ES6 Arrays:An array declaration allocates sequential memory blocks and is static. This means
that an array once initialized cannot be resized.
Arrow Function: Arrow functions are introduced in ES6 which provides you a more accurate
way to write the functions in JavaScript.
Modules of es6: JavaScript modules allow you to break up your code into separate files. This
makes it easier to maintain the code-base.
Virtual DOM:Virtual Document Object Model or virtual DOM. React creates an in-memory
data-structure cache, computes the resulting differences, and then updates the browser's
displayed DOM efficiently.
Self Assessment
5. A class is a type of function, but instead of using the keyword function to initiate it, which
keyword do we use?
A. Constructor
B. Class
C. Object
D. DataObject
11. This folder is the heart of React application as it contains JavaScript which needs to be
processed by webpack
A. Src
B. Public
C. Node_modules
D. package-lock.json
12. This folder contains all dependencies and sub-dependencies specified in package.json used
by React app. It contains more than 800 subfolders, this folder is automatically added in the
.gitignore file.
A. Src
B. Public
Web Technologies
C. Node_modules
D. package-lock.json
15. Which of the following function is used to change the state of the React.js component?
A. this.setState
B. this.setChangeState
C. this.State{}
D. None of the above.
6. D 7. C 8. A 9. B 10. A
Review Questions
1. What is the virtual DOM?
2. What is the difference between the ES6 and ES5 standards?
3. What is an arrow function and how is it used in React?
4. What are the components in React?
5. What are the differences between class and functional components?
6. What are the advantages of using react?
7. What is the virtual DOM? How does react use the virtual DOM to render the UI?
8. What are the lifecycle methods going to be deprecated in React v16?
9. What are modules explain its types?
10. What objects are in react? Explain?
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross.
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, PhpAndJquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
A function is said to be pure if the return value is determined by its input values only and the
return value is always the same for the same input values.
A React component is said to be pure if it renders the same output for the same state and props. For
React pure class components, React provides the PureComponent base class. Class components that
extend the React.PureComponent classes are treated as pure components.
Pure Components
Pure components have some performance improvements and render optimizations because React
implements they shouldComponentUpdate () method for them with a shallow comparison for
props and state.
Web Technologies
Functional components are very useful in React, especially when we want to isolate state
management from the React component. That’s why they are often called stateless components.
However, functional components cannot leverage the performance improvements and render
optimizations that come with React.PureComponent since they are not classes by definition.
Optimizing a functional component, so that React can treat it as a pure component shouldn’t
necessarily require that the component be converted to a class component. To create a pure
functional component in React, React provides a React.memo () API. Using the React.memo() API,
the React functional component can be wrapped as follows to get React Pure Functional
Component.
Notes:React. Memo () is a higher-order component that takes a React component as its first
argument and returns a pure React component
Requirement of DOM
HTML is used to structure the web pages and JavaScript is used to add behavior to our web pages.
When an HTML file is loaded into the browser, the JavaScript cannot understand the HTML
document directly. So, a corresponding document is created (DOM). DOM is basically the
representation of the same HTML document but in a different format with the use of objects.
JavaScript interprets DOM easily i.e.JavaScript cannot understand the tags(<h1>H</h1>) in HTML
document but can understand object h1 in DOM. Now, JavaScript can access each of the objects (h1,
p, etc) by using different functions.
Object Model
Documents are modeled using objects, and the model includes not only the structure of a document
but also the behavior of a document and the objects of which it is composed of like tag elements
with attributes in HTML.
Properties of DOM
Let’s see the properties of the document object that can be accessed and modified by the document
object.
Properties of DOM
Window Object: Window Object is always at top of the hierarchy.
Document object: When an HTML document is loaded into a window, it becomes a document
object.
Form Object: It is represented by form tags.
Link Object: It is represented by link tags.
Anchor Object: It is represented by a href tags.
Form Control Elements: Form can have many control elements such as text fields, buttons, radio
buttons, and checkboxes, etc.
Model-View-Controller (MVC)
Push vs. Pull Based
Most MVC Frameworks user push-based architecture “action based” (Django, Ruby on Rails,
Symfony, Stripes). Pull-based or “component based” (Lift, Angular2, React)
Backend
All of the awesome that runs your application. Web API involved in running the app. Connection
layer between the frontend and backend. They are connected through API calls (POST, GET, PUT,
etc.). Transmit Content from the Backend to the Frontend commonly in JSON Blobs. Service
Architecture that drives everything (Where all the logic is)
Web Technologies
WebAPI
API stands for Application Programming Interface. It is an application programming interface for
the Web. Browser API can also extend functionality of a web browser. The Server API can extend
the functionality of a web server.
The intermediate layer between front end and back-end systems and it must have an APIswhich
will be consumed by third-party service. We also have to recognize how consumable the API
(Signature, content negotiation) is
Notes:React Element are the smallest building blocks of React apps. An element specifies
what should be there in our UI. An Element is a plain object describing what we want to
appear in terms of the DOM nodes.
For Example:
12.6 JSX
JSX stands for JavaScript XML. It allows us to write HTML in Reactand makes it easier to write and
add HTML.It is easy to make a template using JSX in React, but it's not an easy template language
instead it comes with the complete power of JavaScript.It is faster than normal JavaScript because
it performs optimizations while translating to regular JavaScript. Rather than separating the
markup and logic in separated files, React uses components for this purpose.
Coding in JSX
Web Technologies
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any create
Element() and/or appendChild () methods. It converts HTML tags into react elements. It is not
required to use JSX, but JSX makes it easier to write React applications.
Here are two examples. The first uses JSX and the second do not:
Const myelement = <h1>I Love JSX!</h1>;
ReactDOM.render(myelement,document.GetElementById('root'));
Const myelement = React.createElement('h1', {}, 'I do not use JSX!');
ReactDOM.render (myelement, document.GetElementById('root'));
Expression in JSX
With JSX you can write expressions inside curly braces { }.The expression can be a React variable, or
property, or any other valid JavaScript expression. JSX will execute the expression and return the
result
Example:
Execute the expression 5 + 5:
Const myelement = <h1>React is {5 + 5} times better with JSX</h1>;
Reacts Components
Components are like functions that return HTML elements. They are independent and reusable bits
of code. They serve the same purpose as JavaScript functions, but work in isolation and return
HTML. React components come in two types, Class components and Function components.
When creating a React component, the component's name MUST start with an upper-case letter.A
class component must include the extends React.Component statement is creating an inheritance to
react. They give your component access to react.Component's functionsalso requires a render ()
method, this method returns HTML.
Create a Class component called Car
Class Car extends React. Component
{
render () {
Return<h2>Hi, I am a Car!</h2>;
}
}
Function Component
A Function component also returns HTML, and behaves much the same way as a Class component,
but Function components can be written using much less code, are easier to understand.
Create a Function component called Car
FunctionCar ()
{
Return<h2>Hi, I am a Car!</h2>;
}
Rendering Components
React application has a component called Car, which returns an <h2>element. To use this
component in your application, use similar syntax as normal HTML:
<Car />
Characteristics of React
Flexible
React is remarkably flexible. Once you have learned it, you can use it on a vast variety of platforms
to build quality user interfaces. React is a library, NOT a framework. Its library approach has
allowed React to evolve into such a remarkable tool.
React was created with a single focus: to create components for web applications. A React
component can be anything in your web application like a Button, Text, Label, or Grid.
It has a great developer experience when we start coding in it. Rapid development and React's
small API combined creates a fantastic developer experience.
React's API is very simple to learn. It has very few concepts to learn.
Performance
The React team realized that JavaScript is fast, but updating the DOM makes it slow. React
minimizes DOM changes. And it has figured out the most efficient and intelligent way to update
DOM.
Before React, most frameworks and libraries would update the DOM unintelligently to reflect a
new state. This resulted in changes to a significant portion of the page.
Ease of Testing
React's design is very user friendly for testing.Traditional UI browser testing is a hassle to setup. On
the other hand, you require very little or no configuration for testing in React.Traditional UI
browser requires browsers for testing, but you can test React components quickly and easily using
the node command-line. Browser testing is slow. But command-line testing is fast, and you can run
a considerable amount of test suites at a time.Traditional UI browser testing is often time
consuming and challenging to maintain. React test can be written quickly using tools like Jest &
Enzyme.
React is an excellent tool with which to create interactive applications for mobile, web, and other
platforms.It popularity and usage are increasing day by day for good reason. As a developer,
coding in React makes you better at JavaScript, a language that holds nearly 90% of the web
development share today.
Summary
React component is said to be pure if it renders the same output for the same state and props.
Pure components have some performance improvements and render optimizations.
Functional components are very useful in React, especially when we want to isolate state
management from the React component.
Components are like functions that return HTML elements
React uses Virtual DOM exists which is like a lightweight copy of the actual DOM(a virtual
representation of the DOM).
Web API involved in running the app. Connection layer between the frontend and backend.
A Function component also returns HTML, and behaves much the same way as a Class
component, but Function components can be written using much less code, are easier to
understand
Web Technologies
Keywords
DOM:Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and
style of a document
Pure React: A function is said to be pure if the return value is determined by its input values
only and the return value is always the same for the same input values
Object Model:Documents are modeled using objects, and the model includes not only the
structure of a document but also the behavior of a document and the objects of which it is
composed of like tag elements with attributes in HTML.
JSX:JSX stands for JavaScript XML. It allows us to write HTML in React and makes it easier to
write and add HTML.
Render Function:React renders HTML to the web page by using a function called
ReactDOM.render ().
Virtual DOM: React uses Virtual DOM exists which is like a lightweight copy of the actual
DOM (a virtual representation of the DOM).
Framework: Software Framework designed to reduce overhead in web development
Pure components:It has some performance improvements and render optimizations because
React implements the shouldComponentUpdate() method for them with a shallow
comparison for props and state.
Self Assessment
11. React renders HTML to the web page by using a function called ___
A. ReactDOM.render().
B. DOM.render().
C. ReactDOM().
D. All of the above
Web Technologies
6. C 7. C 8. B 9. A 10. A
Review Questions
1. What is the virtual DOM?
2. What is difference between Pure React and React?
3. What is JSX and how it works?
4. What are the differences between functional and class components?
5. What is the virtual DOM? How does react use the virtual DOM to render the UI?
6. What are the differences between controlled and uncontrolled components?
7. Explain about types of side effects in React component
8. What are the rendering characteristics explain?
9. What are WebAPI? Explain in detail?
10. What is framework and how it is used in React?
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross.
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, PhpAndJquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
Components are like functions that return HTML elements. They are independent and reusable bits
of code. They serve the same purpose as JavaScript functions, but work in isolation and return
HTML.Components come in two types, Class components and Function components.Components
make the task of building UIs much easier. As 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.
Components in React basically return a piece of JSX code by which it tells what should be rendered
on the screen.
React has two types of components:
Functional Components: They are simply JavaScript functions. Function component can be created
We can create a functional component in React by writing a JavaScript function. These functions
may or may not receive data as parameters.
Example shows a valid functional component in React:
Web Technologies
Constgood component=()=>
{
Return<h1>Hello World</h1>;
}
Class Components:The class components are a little more complex than the functional
components. The functional components are not aware of the other components in your program
whereas the class components can work with each other. We can pass data from one class
component to other class components.
Example shows a valid class-based component in React:
Notes: Props are immutable so we cannot modify the props from inside the component.
Inside the components, we can add attributes called props.
When you need immutable data in the component, you have to add props to reactDom.render()
method in the main.js file of your ReactJS project and used it inside the component in which you
need.
String
Array
Integer
Boolean
Object
Function
To send props into a component, use the same syntax as HTML attributes:
Example
Add a "brand" attribute to the Car element:
Const myelement = <Car brand="Ford" />;
• The component receives the argument as a props object:
• Example
• Use the brand attribute in the component:
Function Car(props) {
Return<h2>I am a { props.brand }!</h2>;
}
Props are also how you pass data from one component to another, as parameters.
Example:Send the "brand" property from the Garage component to the Car component:
Function Car (props) {
Return <h2>I am a {props. brand }!</h2>;
}
Function Garage () {
Return (
<>
<h1>Who lives in my garage? </h1>
<Car brand="Ford" />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
Web Technologies
Validators
PropTypes.oneOf() This means the props should be one of several types of specified values.
A simple example to better understand the state management is to analyze a real-time clock
component. The clock component primary job is to show the date and time of a location at the
given instance. As the current time will change every second, the clock component should maintain
the current date and time in it’s state. As the state of the clock component changes every second, the
clock’s render () method will be called every second and the render() method show the current time
using its current state.
State Management
React components have a built-in state object. The state is encapsulated data where you store assets
that are persistent between component renderings.
The state is just a fancy term for a JavaScript data structure. If a user changes state by interacting
with your application, the UI may look completely different afterwards, because it's represented by
this new state rather than the old state.
Redux
Redux was created to resolve this particular issue. it provides a central store that holds all states of
your application. Each component can access the stored state without sending it from one
component to another.
Reducers in Redux
Web Technologies
Reducers specify how the application's state changes in response to actions sent to the store. The
store holds the application state. You can access stored state, update the state, and register or
unregister listeners via helper methods.Redux gives you code organization and debugging
superpowers. This makes it easier to build more maintainable code, and much easier to track down
the root cause when something goes wrong.
React Hook
These are functions that hook you into React state and features from function components. Hooks
don't work inside classes and it allows you to use React features without writing a class.
Hooks are backwards-compatible, which means it doesn't keep any breaking changes. React
provides some built-in Hooks like useState, UseEffect and useReducer etc. You can also make
custom hooks.
Handling events with react have some differences from handling events on DOM. These are:
Events can be added in React. They can be written in camel Case syntax
FunctionFootball ()
{
Const shoot = () => {
alert ("Great Shot!");
}
Return (
<button onClick= {shoot}>Take the shot!</button>
);
}
ReactDOM.render(<Football />, document.getElementById('root'));
If else statement
An if…else statement will execute the actions contained in the if block when the condition is
satisfied. Otherwise, it will execute the actions contained in the else block.
In JSX, you are able to use JavaScript code with markup to render dynamic values within your
application. JSX uses curly braces ({ and }) to signify expressions that need to be interpreted prior to
rendering. The caveat, however, is that there is a limit to what can be done within such braces.
Import React from 'react';
Import ReactDOM from 'react-dom/client';
Functionhello () {
Return<h1>Hello!</h1>;
}
Web Technologies
Functionworld () {
Return<h1>there!</h1>;
}
function day(props) {
Constisday = props.isday;
if (isday) {
Return<There/>;
}
Return<Hello/>;
}
Switch Statement
You can conditionally return different markup from a component based on set conditions using an
if…else statement. The same could be achieved with a switch statement where you can specify the
markup for various conditions.
Ternary Operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands. This
operator is frequently used as a shortcut for the if statement
React Forms
Forms are an integral part of any modern web application. It allows the users to interact with the
application as well as gather information from the users. Forms can perform many tasks that
depend on the nature of your business requirements and logic such as authentication of the user,
adding user, searching, filtering, booking, ordering, etc. A form can contain text fields, buttons,
checkbox, radio button, etc.
Creating Forms
React offers a stateful, reactive approach to build a form. The component rather than the DOM
usually handles the React form. In React, the form is usually implemented by using controlled
components.
There are mainly two types of form input in React
Uncontrolled Component- The uncontrolled input is similar to the traditional HTML form inputs.
The DOM itself handles the form data. The HTML elements maintain their own state that will be
updated when the input value changes. To write an uncontrolled component, you need to use a ref
to get form values from the DOM. In other words, there is no need to write an event handler for
every state update. We can use a ref to access the input field value of the form from the DOM.
Notes:To write an uncontrolled component, you need to use a ref to get form values from
the DOM.
Controlled Component-Controlled components have functions that govern the data passing into
them on every on-Change event, rather than grabbing the data only once, e.g., when you click a
submit button. This data is then saved to state and updated with set State () method. This makes
component have better control over the form elements and data. A controlled component takes its
current value through props and notifies the changes through callbacks like an on-Change event.
A parent component "controls" these changes by handling the callback and managing its own state
and then passing the new values as props to the controlled component. It is also called as a "dumb
component."
Handling Forms
Handling forms is about how you handle the data when it changes value or gets submitted.In
HTML, form data is usually handled by the DOM.In React, form data is usually handled by the
components.
Example:
Function Car (props) {
Return <li>I am a { props. brand }</li>;}
Function Garage() { const cars = ['Ford', 'BMW', 'Audi'];
Web Technologies
Return (
<><h1>who lives in my garage? </h1>
<ul>
{cars.map((car) =><Car brand={car} />)}
</ul>
</>
);
}
Creating Form
React offers a stateful, reactive approach to build a form. The component rather than the DOM
usually handles the React form. In React, the form is usually implemented by using controlled
components.
There are mainly two types of form input in React.
Uncontrolled Component
Controlled Component
Uncontrolled Component- The uncontrolled input is similar to the traditional HTML form inputs.
The DOM itself handles the form data. The HTML elements maintain their own state that will be
updated when the input value changes. To write an uncontrolled component, you need to use a ref
to get form values from the DOM. In other words, there is no need to write an event handler for
every state update. You can use a ref to access the input field value of the form from the DOM.
Controlled Component- In HTML, form elements typically maintain their own state and update it
according to the user input. In the controlled component, the input form element is handled by the
component rather than the DOM.The mutable state is kept in the state property and will be
updated only with set State () method. Controlled components have functions that govern the data
passing into them on every on Change event, rather than grabbing the data only once, e.g., when
you click a submit button. This data is then saved to state and updated with set State () method.
This makes component have better control over the form elements and data.
A controlled component takes its current value through props and notifies the changes through
callbacks like an on Change event. A parent component "controls" this changes by handling the
callback and managing its own state and then passing the new values as props to the controlled
component. It is also called as a "dumb component."
Example of Forms
FunctionMy Form () {
Return (
<Form>
<Label>Enter your name:
<input type="text" />
</label>
</form>
)
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
Summary
Components are like functions that return HTML elements. They are independent and
reusable bits of code.
Properties validation is a useful way to force the correct usage of the components.
Handling events with react have some differences from handling events on DOM
Forms can perform many tasks that depend on the nature of your business requirements and
logic such as authentication of the user, adding user, searching, filtering, booking, and
ordering.
React offers a stateful, reactive approach to build a form. The component rather than the DOM
usually handles the React form.
React components have a built-in state object. The state is encapsulated data where you store
assets that are persistent between component renderings.
Handling forms is about how you handle the data when it changes value or gets submitted.
Keywords
Component:Components in React basically return a piece of JSX code by which it tells what
should be rendered on the screen.
Functional Components: They are simply JavaScript functions. Function component can be
created
Class Components: The class components are a little more complex than the functional
components.
Props: They are read-only components. It is an object which stores the value of attributes of a
tag and work similar to the HTML attributes.
React Forms: Forms are an integral part of any modern web application. It allows the users to
interact with the application as well as gather information from the users.
Handling Forms:Handling forms is about how you handle the data when it changes value or
gets submitted.
Uncontrolled Components: The uncontrolled input is similar to the traditional HTML form
inputs.
Handling Forms: Handling forms is about how you handle the data when it changes value or
gets submitted.
Web Technologies
Self Assessment
A. 1
B. 3
C. 4
D. 5
11. ______are a new feature added in React v16.8. It allows to use all React features without
writing class components.
A. Hooks
B. Props
C. State
D. All of above
12. __________ is a Javascript framework built using Typescript, while Reactjs is a Javascript
A. Angular
B. Pro
C. Milt
D. All of the above
13. The conditional operator is the only JavaScript operator that takes three operands.
A. Ternary
B. Primary
C. Tertiary
D. All of the above
14. ________are used to display data in an ordered format and mainly used to display menus on
websites
A. Lists
B. Props
C. Component
D. None of above
15. ______are an integral part of any modern web application. It allows the users to interact with
the application as well as gather information from the users.
A. Lists
B. Forms
C. Component
D. None of above
Web Technologies
6. B 7. B 8. B 9. A 10. D
Review Questions
1. What is the Component? Explain its Types?
2. Explain how lists work in React
3. How do you create forms in React? Explain with example?
4. How do you implement state in React? How do you update the state of a component?
5. How can you embed two or more components into one?
6. What do you mean by State Management? Explain its components?
7. How to Handle Forms? Explain the creation of forms?
8. What are the differences between state and props?
9. What are the differences between class and functional components?
10. Explain the lifecycle methods of components.
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross.
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, PhpAndJquery,
Second Edition
Web Links
https://www.javascripttutorial.net/javascript-function/
www.webopedia.com
www.web-source.net
Objectives
After studying this unit, you will be able to:
Introduction
Routing is a process of binding a web URL to a specific resource in the web application. It is the
binding of a URL to a component in React. React does not support routing natively as it is basically
an user interface library. React community provides many third-partycomponents to handle
routing in the React application. Let us learn React Router, a top choice routing library for React
application. Components in React basically return a piece of JSX code by which it tells what should
be rendered on the screen. React has two types of components:
14.1 Router
Routing is a process in which a user is directed to different pages based on their action or request.
ReactJS Router is mainly used for developing Single Page Web Applications. React Router is used
to define multiple routes in the application. When a user types a specific URL into the browser and
if this URL path matches any 'route' inside the router file, the user will be redirected to that
particular route. React Router is a standard library system built on top of the React and used to
create routing in the React application using React Router Package.
Router Installation
React contains three different packages for routing.
• react-router: It provides the core routing components and functions for the React Router
applications.
• react-router-native: It is used for mobile applications.
• react-router-dom: It is used for web applications design.
It is not possible to install react-router directly in your application. To use react routing, first, you
need to install react-router-dom modules in your application. The below command is used to install
react router dom.$ npm install react-router-dom --save
Notes:Link in React is similar to anchor tag in html. It sets the target url along with reference
text.
To send props into a component, use the same syntax as HTML attributes:
Example:
Add a "brand" attribute to the Car element:
const myelement = <Car brand="Ford" />;
• The component receives the argument as a props object:
• Example
• Use the brand attribute in the component:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
Props are also how you pass data from one component to another, as parameters.
Example
Send the "brand" property from the Garage component to the Car component:
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand="Ford" />
</>
);
}
ReactDOM.render(<Garage />, document.getElementById('root'));
<BrowserRouter>:
BrowerRouter is a router implementation that has the ability to incorporate routing in react.It uses
the HTML5 History API which include pushState, replaceState and the popState event to keep our
UI in sync with the URL.It is the parent component that is used to store all other components and it
uses regular URL paths.
<Route>:
Route is the conditional component that renders a component based on the URL defined or the
URL it is pointing to.In other words, it is a component that renders some UI when its path matches
the current URL.
<Link>:
Link component is used to create links to different routes and implements navigation around the
application. Links accepts the to prop, which signifies where we want the link to navigate our user
to.
<Switch>:
The switch component is used to render only the first route that matches the location rather than
rendering all matching routes.
This is one increasingly common way of having a more seamless user experience. React router also
allows the user to utilize browser functionality like the back button and the refresh page while
maintaining the correct view of the application.
Folder Structure
Within the src folder, we'll create a folder named pages with several files:
• src\pages\:
• Layout.js
• Home.js
• Blogs.js
• Contact.js
• NoPage.js
• Each file will contain a very basic React component.
Basic Usage
Now use Router in our index.js file.
Example:
• Use React Router to route to pages based on URL:
• import ReactDOM from "react-dom";
• import { BrowserRouter, Routes, Route } from "react-router-dom";
• Now use Router in our index.js file.
Example
• import Layout from "./pages/Layout";
• import Home from "./pages/Home";
• import Blogs from "./pages/Blogs";
• import Contact from "./pages/Contact";
• importNoPagefrom "./pages/NoPage";
Pros
Routing between components is fast as the amount of data that renders is less. The rest of the data
is rendered by the DOM, and even when there's tons of HTML and CSS to render, the DOM
handles that part in the blink of an eye. Using lazy loading, any delay in rendering HTML is
compensated for better user experience, animations and transitions can be easily implemented
when switching between different components.It gives a real sense of a single-page application in
action. No separate pages are rendered, and the current page doesn't refresh to load a new view
Cons
The initial loading time is considerably large as all the routes, components, and HTML have to be
loaded at once when the application first mounts. The whole website or web app needs to be
loaded on the first request.There is unnecessary data download time for unusable views that cannot
be anticipated on the first render of the application.It generally requires an external library, which
means more code and more dependency on external packages, unlike routing on the server-
side.Client-side routing and rendering convert JavaScript to HTML, making search engine crawling
less optimized.
Notes: To write an uncontrolled component, you need to use a ref to get form values from the
DOM.
Components of React
React code is made of entities called components. These components are reusable and must be
formed in the SRC folder following the Pascal Case as its naming conversion.Components can be
rendered to a particular element in the DOM using the React DOM library.
Virtual DOM
Another notable feature is the use of a virtual Document Object Model, or virtual DOM. React
creates an in-memory data-structure cache, computes the resulting differences, and then updates
the browser's displayed DOM efficiently. This process is called reconciliation.
What is Gitignore?
The .gitignore file tells Git which files to ignore when committing your project to the GitHub
repository. gitignore is located in the root directory of your repo. / will ignore directories with the
name.Ignored files are usually build artifacts and machine generated files that can be derived from
your repository source or should otherwise not be committed
What is ES6?
ES6 stands for ECMAScript 6.ECMAScript was created to standardize JavaScript, and ES6 is the 6th
version of ECMAScript, it was published in 2015, and is also known as ECMAScript
2015.ECMAScript (European Computer Manufacturers Association Script) is a scripting language
based on JavaScript. Invented by Brendan Eich at Netscape, ECMAScript made its first appearance
in the Navigator 2.0 browser.ES6 allows you to write the code in such a way that makes your code
more modern and readable. By using ES6 features, we write less and do more, so the term 'Write
less, do more' suits ES6. ES6 introduces you many great features such as scope variable, arrow
functions, template strings, class destructions, modules, etc.
React E6 Classes
Classes are an essential part of object-oriented programming (OOP). Classes are used to define the
blueprint for real-world object modeling and organize the code into reusable and logical
parts.Before ES6, it was hard to create a class in JavaScript. But in ES6, we can create the class by
using the class keyword. We can include classes in our code either by class expression or by using a
class declaration.
Notes: A class is a type of function, but instead of using the keyword function to initiate it, we
use the keyword class, and the properties are assigned inside a constructor() method.
Arrow functions are introduced in ES6, which provides you a more accurate way to write the
functions in JavaScript. They allow us to write smaller function syntax. Arrow functions make your
code more readable and structured.Arrow functions are anonymous functions (the functions
without a name and not bound with an identifier). They don't return any value and can declare
without the function keyword. Arrow functions cannot be used as the constructors.
Export
Keywords
Router:Routing is a process in which a user is directed to different pages based on their action or
request. ReactJS Router is mainly used for developing Single Page Web Applications
Browser Router: BrowerRouter is a router implementation that has the ability to incorporate
routing in react.
React Router: React Router is an API for React applications. Most current code is written with React
Router 3, although version 4 has been released. React Router uses dynamic routing
React Java Library:React can be used as a base in the development of single-page or mobile
applications.
LINK: Link component is used to create links to different routes and implements navigation
around the application. Links accepts the to prop, which signifies where we want the link to
navigate our user to.
Gitinore: The.gitignore file tells Git which files to ignore when committing your project to the
GitHub repository.
Export:You can export a function or variable from any file.Let us create a file named person.js, and
fill it with the things we want to export.
Summary
Routing is a process in which a user is directed to different pages based on their action or
request. ReactJS Router is mainly used for developing Single Page Web Applications
React Router plays an important role to display multiple views in a single page application.
Without React Router, it is not possible to display multiple views in React applications
Gi ignore file tells Git which files to ignore when committing your project to the GitHub
repository.
npm is the package manager for the Node JavaScript platform. It puts modules in place so
that node can find them, and manages dependency conflicts intelligently
The name of a JavaScript library is ReactDOM. This library includes a number of React-
specific methods that all deal with the DOM in some way.
ECMAScript (or ES) is a standard for scripting languages such as JavaScript, ActionScript,
and JScript developed by the European Computer Manufacturers Association. It was
originally intended to standardize JavaScript, which is the most widely used ECMAScript
implementation.
Self Assessment
1. _______is a process in which a user is directed to different pages based on their action or
request.
A. Routing
B. Stating
C. Propes
D. All of the above
5. Which provides the core routing components and functions for the React
Routerapplications.
A. react-router:
B. react-router-native:
C. react-router-dom:
D. all of the above
8. _________is a router implementation that has the ability to incorporate routing in react.
A. BrowerRouter
B. Switch
C. Link
D. All of the above
9. ________is the conditional component that renders a component based on the URL defined
or the URL it is pointing to.
A. BrowerRouter
B. Switch
C. Route
D. All of the above
10. __________component is used to create links to different routes and implements navigation
around the application.
A. Brower Router
B. Switch
C. Link
D. All of the above
11. The _________component is used to render only the first route that matches the location
rather than rendering all matching routes.
A. BrowerRouter
B. Switch
C. Link
D. All of the above
12. ________is annpm package that enables you to implement dynamic routing in a web app.
A. React Router DOM
B. Dom
C. Router
D. None of the above
6. B 7. C 8. A 9. C 10. C
Review Questions
1. How we render the routre? Explain its Types?
2. Explain npm in React?
3. How we can install react? Explain its steps?
4. How we implement Router in React?
5. What is Gitinore?
6. What are Routers Parameters?
7. What is react-router-dom? Explain?
8. What Happens When You Need to Navigate TWO Routing System?
9. How we can add react router?
10. Explain the need of React Router?
Further Readings
HTMl, JavaScript , DHTML and PHP By. Ivan Bayross.
Beginning JavaScript 2nd Edition By. Paul Wilton
Html 5 Black Book, Covers Css 3, Javascript, Xml, Xhtml, Ajax, PhpAndJquery, Second
Edition
Web Links
https://www.javascripttutorial.net/javascript-function/