You are on page 1of 145

INDIRA GANDHI COLLEGE OF ARTS AND SCIENCE

(AFFILIATED TO PONDICHERRY UNIVERSITY)


PUDUCHERRY-605 009
( ACCREDITED WITH B+, NAAC)

DEPARTMENT OF COMPUTER SCIENCE


BACHELOR OF COMPUTER APPLICATIONS (B.C.A)

RECORD OF PRACTICALS

NAME : ……………………………….….
REGISTER NUMBER: ……………………………………..
SEMESTER : …………………………………..
YEAR : …………………………………..
SUBJECT : …………………………………..
INDIRA GANDHI COLLEGE OF ARTS AND SCIENCE
(AFFILIATED TO PONDICHERRY UNIVERSITY)
PUDUCHERRY-605 009
( ACCREDITED WITH B+, NAAC)

DEPARTMENT OF COMPUTER SCIENCE


BACHELOR OF COMPUTER APPLICATIONS (B.C.A)

BONAFIDE CERTIFICATE
Certified that this is a bonafide record of practical work done by
Selvan / Selvi…………………………………………………………with
register number ……………………… of ………………… during the
………….. semester of the year …………………………

Head of the Department Staff-In-Charge

Submitted for the Practical Examination held on ……………………

Internal Examiner
TABLE OF CONTENT

PAGE
S.No DATE CONTENT SIGNATURE
No

Module 1: Introduction to getting


1. started with web design

Module 2: Write HTML code and


2. create webpages with HTML5

Module 3: CSS and web styling web


3. design

Module 4:Advanced CSS explore


more with CSS3
4.

Module 5: CSS layout flexbox and


5. CSS grid

Module 6: JavaScript Introduction


6.

Module 7: JavaScript DOM


7. Introduction.

Module 8: JavaScript advanced coding


8.
TABLE OF CONTENT

PAGE
S.No DATE CONTENT SIGNATURE
No

Module 9: Coding examples with


9 JavaScript

Module 10: Simple website from


10 starch

Module 11: Fat footer website flex


11

Module 12: CSS grid website with


12 flex navbar

Module 13: Single page website sticky


13 bottom navbar

Module 14: Web design and web


development resources and helpful
14 tips and lessons
Module:1
Introduction to getting started with web design
 Frontend web design and development.
 HTML setup get coding
 Discover how to write HTML code
Module:2
Write HTML code and create webpages with HTML5
 Modern HTML and HTML5 coding
 Resources of HTML
 Create HTML template 2
 HTML elements
 4 headings and bolded text
 6 text formats HTML
 Learn HTML commenting
 HTML Hyperlinks anchor
 HTML mail to send email
 Creating lists in HTML
 Add tables in HTML
 HTML block and inline elements
 HTML5 Semantic elements
 HTML Forms
 Debugging your HTML
Module:3
CSS and web styling web design
 Introduction to CSS
 Adding CSS to web pages and CSS syntax
 CSS for modern web pages
 Ways to apply comments CSS
 CSS selectors
 CSS pseudo classes
 Adding font styles
 Using google fonts CSS
 CSS properties
 Advanced selectors in CSS
Module:4
Advanced CSS explore more with CSS3
 Create CSS linear gradients
 Create CSS radial gradients
 Create CSS 2D transforms
 Animation with CSS Animations
Module:5
CSS layout flexbox and CSS grid
 Create layout with flexbox
 Apply element sizing with flexbox
 Create an image gallery website
 CSS grid to make rows and columns
Module:6
 Start writing code with JavaScript
 JavaScript and HTML
 Add comments in JavaScript
 Output options JavaScript
 Introduction to JavaScript variables
 Let and const variables JavaScript
 Different data types in JavaScript
 JavaScript using backticks
 JavaScript operators
 JavaScript assignment operators
 JavaScript comparison operators
 JavaScript conditional statements
 JavaScript ternary operator
 JavaScript logical operator
 JavaScript switch statement
 JavaScript functions

 JavaScript function parameters


 JavaScript function return
 JavaScript function expression and declaration
 Function scope JavaScript
 JavaScript function recursion
 JavaScript new arrow function
 JavaScript objects
 JavaScript array method
 Create JavaScript loops
 Create values in JavaScript
Module:7
JavaScript DOM Introduction
 Introduction to dynamic and interactive web page content
 Select and element JavaScript DOM
 JavaScript Element selector
 Element Query Selector All JavaScript DOM
 JavaScript Manipulation Inner Content
 Element Attribute Updates using JavaScript
 Manipulate Page elements - JavaScript and Classes
 Remove an Element from your webpage using JavaScript
 JavaScript Web page interactions
Module:8
JavaScript advanced coding
 JavaScript Number Methods
 JavaScript String Methods
 JavaScript Math Object
 JavaScript Date and write the date in JavaScript
 Creating JavaScript prototypes
 Making an AJAX request with JavaScript

Module:9
Coding examples with JavaScript
 Create Page Elements with JavaScript
 Interactive List with JavaScript
 Create List of Elements
 JavaScript Closures data
 Image Gallery with JavaScript
Module:10
Simple website from starch
 Tools and Resources
 Simple Website CSS
 Three Column Website
 Three Column Website Flexbox
 Three Column Website CSS Grid
 HTML form CSS Grid
 Website Review and Conclusion
Module:11
Fat footer website flex
 Website Fat Footer Design
 Setup of HTML Code
 Web Site Wire Frame
 Add Page HTML from Wireframe
 Setup CSS for Page
 Header and Footer Style
 Logo and Nav in Header
 Footer Styling CSS
 Social Icons Font Awesome
 Footer Bottom Copyright Plu
 Website Fat Footer with Flex Conclusion

Module:12
CSS grid website with flex navbar
 Website Planning and Wireframe
 Create Page HTML Structure
 Add CSS Grid
 Responsive navbar
 Apply Styling CSS Fun
 Header Footer CSS
 Add Color and Font Style

Module:13
Single page website sticky bottom navbar
 HTML Setup for Web Page
 HTML Page Structure
 CSS Page Header
 CSS Home Section
 Sections Styling CSS
 Create web Form
 Set Page Footer
 Make Responsive CSS
Module:14
Web design and web development resources and helpful tips and
lessons
 Github and Git Pages Getting started with GitHub and git

Module:1
What is HTML?
 HTML stands for Hyper Text Markup Language
 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements label pieces of content such as "this is a
heading", "this is a paragraph", "this is a link", etc.

HTML Page Structure:


Below is a visualization of an HTML page structure:
<html>
<head>
<title>Page title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph</p>
<p>This is another paragraph</p>
</body>
</html>

Module:2
What is an HTML Element?
An HTML element is defined by a start tag, some content, and an
end tag:
<tag name> Content goes here... </tag name>
The HTML element is everything from the start tag to the end tag:
<h1>My First Heading</h1>
<p>My first paragraph</p>

Start tag Element content End tag

<h1> My first heading </h1>

<p> My first paragraph </p>

<br> none none

Nested HTML Elements

HTML elements can be nested (this means that elements can contain
other elements).
All HTML documents consist of nested HTML elements.
The following example contains four HTML elements (<html>,
<body>, <h1> and <p>):

Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph. </p>
</body>
</html>

Empty HTML Elements

HTML elements with no content are called empty elements.


The <br> tag defines a line break, and is an empty element without a
closing tag:
Example
<p>This is a <br> paragraph with a line break.</p>

HTML is Not Case Sensitive

HTML tags are not case sensitive: <P> means the same as <p>.
The HTML standard does not require lowercase tags, but W3C
recommends lowercase in HTML, and demands lowercase for stricter
document types like XHTML.

HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least
important heading.
Example
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>

HTML Formatting Elements


Formatting elements were designed to display special types of text:
<b> - Bold text
<strong> - Important text
<i> - Italic text
<em> - Emphasized text
<mark> - Marked text
<small> - Smaller text
<del> - Deleted text
<ins> - Inserted text
<sub> - Subscript text
<sup> - Superscript text

HTML <b> and <strong> Elements


The HTML <b> element defines bold text, without any extra
importance.
Example
<b>This text is bold</b>
The HTML <strong> element defines text with strong importance.
The content inside is typically displayed in bold.
Example
<strong>This text is important!</strong>

HTML <i> and <em> Elements


The HTML <i> element defines a part of text in an alternate voice or
mood. The content inside is typically displayed in italic.
Example
<i>This text is italic</i>
The HTML <em> element defines emphasized text. The content
inside is typically displayed in italic.
Example
<em>This text is emphasized</em>

HTML <small> Element


The HTML <small> element defines smaller text:
Example
<small>This is some smaller text.</small>

HTML <mark> Element


The HTML <mark> element defines text that should be marked or
highlighted:
Example
<p>Do not forget to buy <mark>milk</mark> today.</p>

HTML <del> Element


The HTML <del> element defines text that has been deleted from a
document. Browsers will usually strike a line through deleted text:
Example
<p>My favorite color is <del>blue</del> red.</p>

HTML <ins> Element

The HTML <ins> element defines a text that has been inserted into a
document. Browsers will usually underline inserted text:
Example
<p>My favorite color is <del>blue</del> <ins>red</ins>.</p>

HTML <sub> Element

The HTML <sub> element defines subscript text. Subscript text


appears half a character below the normal line, and is sometimes
rendered in a smaller font. Subscript text can be used for chemical
formulas, like H2O:
Example
<p>This is <sub>subscripted</sub> text.</p>

HTML <sup> Element


The HTML <sup> element defines superscript text. Superscript text
appears half a character above the normal line, and is sometimes
rendered in a smaller font. Superscript text can be used for footnotes,
like WWW[1]:
Example
<p>This is <sup>superscripted</sup> text. </p>

HTML <a> Tag


Definition and Usage
The <a> tag defines a hyperlink, which is used to link from one page
to another.
The most important attribute of the <a> element is the href attribute,
which indicates the link's destination.
Example:
<a href="https://www.w3schools.com">Visit W3Schools.com!</a>

HTML Lists
HTML lists allow web developers to group a set of related items in
lists.

HTML List Tags


Tag Description
<ul> Defines an unordered list
<ol> Defines an ordered list
<li> Defines a list item
<dl> Defines a description list
<dt> Defines a term in a description list

<dd> Describes the term in a description list

Unordered HTML List


An unordered list starts with the <ul> tag. Each list item starts with
the <li> tag.
The list items will be marked with bullets (small black circles) by
default:
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Ordered HTML List


An ordered list starts with the <ol> tag. Each list item starts with the
<li> tag.
The list items will be marked with numbers by default:
Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

HTML Description Lists

HTML also supports description lists.


A description list is a list of terms, with a description of each term.
The <dl> tag defines the description list, the <dt> tag defines the term
(name), and the <dd> tag describes each term:
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>

HTML Tables
HTML tables allow web developers to arrange data into rows and
columns.
Fruit name Quantity Amount
Apple 1kg $3.01
Banana 1kg $1.80
Strawberry 1kg $6.01

Define an HTML Table?


A table in HTML consists of table cells inside rows and columns.
A simple HTML table:
<table>
<tr>
<th>Company</th>

<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
Table Cells
 Each table cell is defined by a <td> and a </td> tag.
 td stands for table data.
 Everything between <td> and </td> are the content of the table
cell.
Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

HTML Block and Inline Elements


Every HTML element has a default display value, depending on what
type of element it is.
The two most common display values are block and inline.
Block-level Elements
A block-level element always starts on a new line, and the browsers
automatically add some space (a margin) before and after the element.
A block-level element always takes up the full width available
(stretches out to the left and right as far as it can).
Two commonly used block elements are: <p> and <div>.
The <p> element defines a paragraph in an HTML document.
The <div> element defines a division or a section in an HTML
document.
The <p> element is a block-level element.
The <div> element is a block-level element.
Example
<p>Hello World</p>
<div>Hello World</div>

Block-level elements in HTML:


<address>,<article>,<aside>,<blockquote>,<canvas>,<dd>,<div>,<dl
>,<dt>,<fieldset>,<figcaption>,<figure>,<footer>,<form>,<h1>-
<h6>,<header>,<hr>,<li>,<main>,<nav>,<noscript>,<ol>,<p>,<pre>,
<section>,<table>,<tfoot>,<ul>,<video>

Inline Elements
An inline element does not start on a new line.
An inline element only takes up as much width as necessary.

This is a <span> element inside a paragraph.


Example
<span>Hello World</span>
Inline elements in HTML:
<a><abbr><acronym><b><bdo><big><br><button><cite><code><d
fn><em><i><img><input><kbd><label><map><object><output><q
><samp><script><select><small><span><strong><sub><sup><texta
rea><time><tt><var>

Semantic Elements in HTML


Many web sites contain HTML code like: <div id="nav"> <div
class="header"> <div id="footer"> to indicate navigation, header, and
footer.
In HTML there are some semantic elements that can be used to define
different parts of a web page:
<article>
<aside>
<details>
<fig caption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary><time>

HTML Forms

An HTML form is used to collect user input. The user input is most
often sent to a server for processing.
The <form> Element
The HTML <form> element is used to create an HTML form for user
input:
<form>
.form elements
.form element
</form>
The <form> element is a container for different types of input
elements, such as: text fields, checkboxes, radio buttons, submit
buttons, etc.
The <input> Element
The HTML <input> element is the most used form element.
An <input> element can be displayed in many ways, depending on the
type attribute.
Examples:
Type Description
<input type="text"> Displays a single-line text input field
<input type="radio"> Displays a radio button (for selecting one of
many choices)
<input type="checkbox"> Displays a checkbox (for selecting zero or
more of many choices)
<input type="submit"> Displays a submit button (for submitting
the form)
<input type="button"> Displays a clickable button

Text Fields
The <input type="text"> defines a single-line input field for text
input.
Example
A form with input fields for text:
<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>
OUTPUT:
First name:
Last name:

The <label> Element


The <label> tag defines a label for many form elements.
The <label> element is useful for screen-reader users, because the
screen-reader will read out loud the label when the user focuses on the
input element.
The <label> element also helps users who have difficulty clicking on
very small regions (such as radio buttons or checkboxes) – because
when the user clicks the text within the <label> element, it toggles the
radio button/checkbox.
The for attribute of the <label> tag should be equal to the id attribute
of the <input> element to bind them together.

Radio Buttons
The <input type="radio"> defines a radio button.
Radio buttons let a user select ONE of a limited number of choices.
Example
A form with radio buttons:
<p>Choose your favorite Web language:</p>
<form>
<input type="radio" id="html" name="fav_language"
value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language"
value="JavaScript">
<label for="javascript">JavaScript</label>
</form>
OUTPUT:
Choose your favorite Web language:
o HTML
o CSS
o JavaScript

Checkboxes
The <input type="checkbox"> defines a checkbox.
Checkboxes let a user select ZERO or MORE options of a limited
number of choices.
Example
A form with checkboxes:

<form>
<input type="checkbox" id="vehicle1" name="vehicle1"
value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2"
value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3"
value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
OUTPUT:
 I have a bike
 I have a car
 I have a boat

The Submit Button


The <input type="submit"> defines a button for submitting the form
data to a form-handler.
The form-handler is typically a file on the server with a script for
processing input data.
The form-handler is specified in the form's action attribute.
Example
A form with a submit button:
<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>

<input type="text" id="lname" name="lname"


value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
OUTPUT:
First name: John
Last name: Doe
Submit

EX:1 SIMPLE TAGS IN HTML

<html>
<head>
<title>Basic Tag</title>
</head>
<body>
<font face="Prepetua Titling MT" color="#ff0c7c">
<h1 align="center">Slogans</h1>
</font><br>
<h2>Master Card</h2>
<p>
<font face="Segoe UI Light" Size="4">
'There are some things <b>money can't buy</b> For everything
else, there's <b><i>Master Card</i></b>'
</font>
</p>
<h2>Apple</h2>
<p>
<font face="Segoe UI Light" Size="4">
'<i>Think Different</i>'
</font>
</p>
<h2>Audi</h2>
<p>
<font face="Segoe UI Light" Size="4">
'Advancement Through <strong> Technology</strong>'

</font>
</p><hr><br>
WATER = H<sub>2</sub>O <br>
(a+b)<sup>2</sup> = a<sup>2</sup> + 2ab + b<sup>2</sup>
<br><br><hr>
<address>
No: 32, New St, <br>Anna Nagar <br> Chennai-600040
</address>
</body>
</html

OUTPUT:

EX:2 ORDERED LIST AND UNORDERED LIST

<html>
<head>
<title>List</title>
</head>
<body>
<h1>Diary Group</h1>
<ol type="I">
<li>Milk</li>
<li>Yogurt</li>
<li>Cheese</li>
<li>Butter</li>
<li>Cream</li>
</ol>
<h1>Beverages</h1>
<ul type="circle">
<li>Tea</li>
<li>Coffee</li>
<li>Cola</li>
</ul>
<dl>
<dt>Tea</dt>
<dd>"A Cup of Tea is a Cup of Peace"</dd>
<dt>Coffee</dt>
<dd>"The Gasoline of Life"</dd>
</dl>

</body>
</html>
OUTPUT:

EX:3 TABLE IN HTML

<html>
<head>
<title>Student_Strength</title>
</head>
<body bgcolor="#d7fbf1">
<br><br>
<table border="2px" bordercolor="grey">
<thead>
<tr>
<td colspan="6" style="text-align: center">
STUDENT TOTAL STRENGTH
</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="6">
This Table will show the Details About the Total Strength of the
Students in this College
</td>
</tr>
</tfoot>
<tbody>
<tr>
<th width="80">Year</th>

<th>BAM</th>
<th>BBT</th>
<th>BCA</th>
<th>BFT</th>
<th>BST</th>
</tr>
<tr>
<th>I Year</th>
<td>60</td>
<td>60</td>
<td>60</td>
<td>120</td>
<td>60</td>
</tr>
<tr>
<th>II Year</th>
<td>60</td>
<td>60</td>
<td>60</td>
<td>120</td>
<td>60</td>
</tr>
<tr>
<th>III Year</th>
<td>60</td>
<td>60</td>
<td>60</td>

<td>120</td>
<td>60</td>
</tr>
<tr>
<th>TOTAL</th>
<td>180</td>
<td>180</td>
<td>180</td>
<td>360</td>
<td>180</td>
</tr>
</tbody>
</table>
</body>
</html>

OUTPUT:
EX:4 FORMS IN HTML

<html>
<head>
<title>Form1</title>
</head>
<body bgcolor="pink">
<h3 align="center">
Application Form <br>
(For International Conferrence)
</h3>
<br>
<form>
<b>First Name</b> : <input type="text" name="fname" /> <br><br>
<b>Last Name</b> : <input type="text" name="lname" />
<br /><br>
<b>Gender</b> :
<input type="radio" name="Gender" value="male" />Male
<input type="radio" name="Gender" value="female" />Female
<br /><br>
<b>Mobile No</b> : <input type="text"><br><br>
<b>Year</b> : <select name="dropdown">
<option value="Select">--select--</option>
<option value="year1">I YEAR</option>
<option value="year2">II YEAR</option>
<option value="year3">III YEAR</option>
</select>

<br><br>
<b>Topic</b> : <br><br>
<textarea name="topic" cols="30" rows="3"></textarea>
<br><br>
<b>Timming</b> : (Choose your convinent Timimng) <br><br>
<input type="checkbox"> 10:00 To 11:30 AM
<input type="checkbox"> 11:30 To 12:00 AM <br><br>
<input type="checkbox"> 12:00 To 01:30 PM
<input type="checkbox"> 01:30 To 03:00 PM
<br><br><br>
<b>Payment Mode</b> : <br><br>
<p style="margin-left: 20px;">
<input type="radio" name="payment" value="card">
Debit/Credit Card <br><br>
<p style="margin-left: 50px;">
Card No :
<input type="text" name="card_no" maxlength="16" size="16" />
<br><br>
CCV No :
<input type="text" name="ccv_no" maxlength="3" size="3" />
<br><br>
PIN :
<input type="password" name="pin" maxlength="4" size="4" />
<br><br>
</p>
</p>
<p style="margin-left: 80px;">
(OR) <br><br>

</p>
<p style="margin-left: 20px;">
<input type="radio" name="payment" value="acc_transfer"/>
Online Bank Transaction <br><br>
<p style="margin-left: 50px;">
Account No:
<input type="text" name="acc_no" maxlength="16" size="16" />
<br><br>
User ID : <input type="text" name="user_id" /> <br><br>
Password :
<input type="password" name="password" maxlength="8" size="8" >
<br><br></p>
</p>
Upload Photo :
<input type="file" name="photo" accept = "images/*"><br><br>
<b>Lunch</b> : <input type="radio" name="lunch"
value="veg"/>Veg
<input type="radio" name="lunch" value="non_veg"/>Non-Veg
<br><br>
<button>Submit</button>
</form>
</body>
</html>

OUTPUT:
EX:5 CREATING WEBSITE USING HTML TAGS
MAIN PAGE:
<html>
<head>
<title>document</title>
<link rel="stylesheet" href="myclass.css">
</head>
<body background="ice.png"/>
<header>
<center><b> <h1>HEAVEN</h1></b>
<i><h2>Melts on your mouth</i>
<p>No:7,white town,pondicherry-605110</p><h2></center>
</header>
<section>
<a href="aboutus.html">
<h1>ABOUT US</h1></a><br>
<a href="main.html">
<h1>OUR LOVES</h1></a><br>
<a href="form.html">
<h1>CUSTOMIZE YOUR<BR> OWN ICE CREAM</h1></a>
</section>
<footer>
<i>contact us Ph:0987654321,Mail:heavenicecream@gmail.com</i>
</footer>
</body>
</html>

ABOUT US
<html>
<head>
<title>about us</title>
</head>
<body style="background-color:lavender">
<center><img src="heaven.jpg" width="50%"
height="50%"></center>
<center><p><h1>we have both chocolates and ice creams</h1></p>
<p><h1>you can customize your ice creams</h1></p>
<p><h2>FLAVOURS</h2></p>
<ul>
<h3><li>vannila
<li>starwberry
<li>chocolate
<li>butterscoch
<li>blueberry
<li>fruit and nut</center><h3>
</ul>
</body>
</html>

FORM:
<html>
<head>
<title>form</title>

</head>
<body style="background-color:lavender">
<script type="text/javascript">
<form>
FIRST NAME:<input name="text"><br><br>
SECOND NAME:<input name="text"><br><br>
MOBILE NUMBER:<input name="text"><br><br>
ADDRESS:<input name="text"><br><br>
FLAVOURS:<br><input type="checkbox">chocolate<br>
<input type="checkbox">vannila<br>
<input type="checkbox">starwberry<br>
<input type="checkbox">butterscoch<br>
<input type="checkbox">blueberry<br>
<input type="checkbox">blackcurrent<br><br>
TOPINGS:<br><input type="checkbox">chocolate<br>
<input type="checkbox">kissbiss<br>
<input type="checkbox">starwberry<br>
<input type="checkbox">dry fruits<br>
<input type="checkbox">sugar balls<br>
<input type="checkbox">brownie<br><br>
QUANTITY:<br><input type="radio" name="qut">200gm<br>
<input type="radio" name="qut">300gm<br>
<input type="radio" name="qut">500gm<br>
<input type="radio" name="qut">600gm<br>
<input type="radio" name="qut">700gm<br>
<input type="radio" name="qut">1000gm<br><br>

PAYMENT :
<input type="radio" name="pay">By Cash<br>
<input type="radio" name="pay">Debit Card<br>
<input type="radio" name="pay">Cedit Card<br>
<input type="radio" name="pay">Online
Payment<br><br>
<input type="button" value="SUBMIT" >
</form>
</body>
</html>

DISCOUNT
<html>
<head>
<title>MAIN</title>
</head>
<body style="background-color: lavender">
<center> <H1>OUR LOVES</H1>
<marquee position="down">FEEL THE HEAVEN ON YOUR
TOUNGE</marquee>
<br>
<br>
<br>
<h2><p>WE GIVE QUALITY ICE CREAMS AT LOW
COST</P>
<p>SAMPLES HAS BEEN GIVEN</P>
<P>DISCOUNT ON PURCHASES ABOVE 500</P>

<P>CUSTOMERS SATISFACTION IS OUR


SATISFACTION</P></center></h2>
</BODY>
</HTML>

OUTPUT:
Module:3

What is CSS?
 CSS stands for Cascading Style Sheets
 CSS describes how HTML elements are to be displayed on
screen, paper, or in other media
 CSS saves a lot of work. It can control the layout of multiple
web pages all at once
 External stylesheets are stored in CSS files
CSS Syntax

CSS selector
The selector points to the HTML element you want to style.
The declaration block contains one or more declarations separated by
semicolons.
Each declaration includes a CSS property name and a value, separated
by a colon.
Multiple CSS declarations are separated with semicolons, and
declaration blocks are surrounded by curly braces.
Example
In this example all <p> elements will be center-aligned, with a red
text color:
p{
color: red;
text-align: center;}
CSS Comments

Comments are used to explain the code, and may help when you edit
the source code at a later date.
Comments are ignored by browsers.
A CSS comment is placed inside the <style> element, and starts
with /* and ends with */:
Example
/* This is a single-line comment */
p{
color: red;
}
You can add comments wherever you want in the code:
Example
p{
color: red; /* Set text color to red */
}
Even in the middle of a code line:
Example
p{
color: /*red*/blue;
}
Comments can also span multiple lines:
Example
/* This is
a multi-line
comment */
p{
color: red;
}

HTML CSS COMMENTS:


Example
<!DOCTYPE html>
<html>
<head>
<style>
p{
color: red; /* Set text color to red */
}
</style>
</head>
<body>
<h2>My Heading</h2>
<!-- These paragraphs will be red -->
<p>Hello World! </p>
<p>This paragraph is styled with CSS.</p>
<p>CSS comments are not shown in the output</p>
</body>
</html>
CSS Selectors

 CSS selectors are used to "find" (or select) the HTML elements
you want to style.
 We can divide CSS selectors into five categories:
 Simple selectors (select elements based on name, id, class)
 Combinator selectors (select elements based on a specific
relationship between them)
 Pseudo-class selectors (select elements based on a certain state)
 Pseudo-elements selectors (select and style a part of an element)
 Attribute selectors (select elements based on an attribute or
attribute value)

Basic CSS selectors

 The CSS element Selector


The element selector selects HTML elements based on the
element name.
Example
Here, all <p> elements on the page will be center-aligned, with a red
text color:
p{
text-align: center;
color: red;
}
 The CSS id Selector
The id selector uses the id attribute of an HTML element to
select a specific element.
The id of an element is unique within a page, so the id selector is used
to select one unique element!
To select an element with a specific id, write a hash (#) character,
followed by the id of the element.
Example
The CSS rule below will be applied to the HTML element with
id="para1":
#para1 {
text-align: center;
color: red;
}

 The CSS class Selector


The class selector selects HTML elements with a specific class
attribute.
To select elements with a specific class, write a period (.) character,
followed by the class name.
Example
In this example all HTML elements with class="center" will be red
and center-aligned:
.center {
text-align: center;
color: red;
}
Example
In this example only <p> elements with class="center" will be red and
center-aligned:
p.center {
text-align: center;
color: red;
}
HTML elements can also refer to more than one class.
Example
In this example the <p> element will be styled according to
class="center" and to class="large":
<p class="center large">This paragraph refers to two classes.</p>

 The CSS Universal Selector


The universal selector (*) selects all HTML elements on the
page.
Example
The CSS rule below will affect every HTML element on the page:
*{
text-align: center;
color: blue;
}

 The CSS Grouping Selector


The grouping selector selects all the HTML elements with the
same style definitions.
h1 {
text-align: center;
color: red;
}
h2 {
text-align: center;
color: red;
}
p{
text-align: center;
color: red;
}
It will be better to group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
Example
In this example we have grouped the selectors from the code above:
h1, h2, p {
text-align: center;
color: red;
}

CSS Fonts
Font Selection is Important
Choosing the right font has a huge impact on how the readers
experience a website.
The right font can create a strong identity for your brand.
Using a font that is easy to read is important. The font adds value to
your text. It is also important to choose the correct color and text size
for the font.
 Generic Font Families
In CSS there are five generic font families:
 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.
Some Font Examples
 Generic Font Family Examples of Font Names
 Serif Times New Roman
 Georgia
 Garamond
 Sans-serif Arial
 Verdana
 Helvetica
 Monospace
 Lucida Console
 Monaco
 Cursive Brush Script MT
 Lucida Handwriting
 Fantasy

Example
Specify some different fonts for three paragraphs:
.p1 {
font-family: "Times New Roman", Times, serif;
}
.p2 {
font-family: Arial, Helvetica, sans-serif;
}
.p3 {
font-family: "Lucida Console", "Courier New", monospace;
}

Module:4

CSS linear-gradient() Function

Definition and Usage


The linear-gradient() function sets a linear gradient as the background
image.
To create a linear gradient you must define at least two color stops.
Color stops are the colors you want to render smooth transitions
among. You can also set a starting point and a direction (or an angle)
along with the gradient effect.
Example
This linear gradient starts at the top. It starts red, transitioning to
yellow, then to blue:
#grad {
background-image: linear-gradient(red, yellow, blue);
}

CSS Radial Gradients

A radial gradient is defined by its center.


To create a radial gradient you must also define at least two color
stops.
Syntax
background-image: radial-gradient(shape size at position, start-
color, ..., last-color);
By default, shape is ellipse, size is farthest-corner, and position is
center.
Radial Gradient - Evenly Spaced Color Stops (this is default)
Example
#grad {
background-image: radial-gradient(red, yellow, green);
}

#grad {
background-image: radial-gradient(circle, red, yellow, green);
}

Module:5

CSS Flexbox Layout Module

 Before the Flexbox Layout module, there were four layout


modes:
 Block, for sections in a webpage
 Inline, for text
 Table, for two-dimensional table data
 Positioned, for explicit position of an element
 The Flexible Box Layout Module, makes it easier to design
flexible responsive layout structure without using float or
positioning.
Example
A flex container with three flex items:
<div class="flex-container">
<div>1</div>
<div>2</div>
<div>3</div>
</div>

Image Gallery
The following image gallery is created with CSS:
Example
<html>
<head>
<style>
div.gallery {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}
div.gallery:hover {
border: 1px solid #777;
}
div.gallery img {
width: 100%;
height: auto;
}
div.desc {
padding: 15px;
text-align: center;
}
</style>
</head>
<body>
<div class="gallery">
<a target="_blank" href="img_5terre.jpg">
<img src="img_5terre.jpg" alt="Cinque Terre" width="600"
height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_forest.jpg">
<img src="img_forest.jpg" alt="Forest" width="600"
height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_lights.jpg">
<img src="img_lights.jpg" alt="Northern Lights" width="600"
height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
<div class="gallery">
<a target="_blank" href="img_mountains.jpg">
<img src="img_mountains.jpg" alt="Mountains" width="600"
height="400">
</a>
<div class="desc">Add a description of the image here</div>
</div>
</body>
</html>

Grid Layout
The CSS Grid Layout Module offers a grid-based layout system, with
rows and columns, making it easier to design web pages without
having to use floats and positioning.

Grid Elements
A grid layout consists of a parent element, with one or more child
elements.

Example
<div class="grid-container">
<div class="grid-item">1</div>
<div class="grid-item">2</div>
<div class="grid-item">3</div>
<div class="grid-item">4</div>
<div class="grid-item">5</div>
<div class="grid-item">6</div>
<div class="grid-item">7</div>
<div class="grid-item">8</div>
<div class="grid-item">9</div>
</div>
EX:6 CSS CASCADING STYLE SHEET

<html>
<head>
<title>Tribute</title>
<link rel="Stylesheet" href="mycss.css">
<style>
*{
font-family: Times New Roman
}
body {
background-color: #01bdec;
margin: 20%;
}
#image {
display: inline-block;
width: 100%;
}
</style>
</head>
<body>
<h1 id="title">
A. P. J. Abdul Kalam
</h1>
<div id="image">
<!--Image of the Tribute Person-->
<img src="abdul-kalam.png"
id="image" alt="Error Loading Image">
<small style="font-size: 19px; font-family: Gill Sans; color:rgb(73,
252,
162);">
Great Indian scientist and
politician who played a leading
role in the development of India’s
missile and nuclear weapons
programs.
</small>
</div>
<div class="tribute-data">
<h1 class="title-APJ">
About the Legend
</h1>
<p>
☛ A.P.J. Abdul Kalam, in full Avul Pakir Jainulabdeen Abdul Kalam,
was
born on October 15, 1931, in Rameswaram, Tamil Nadu,
India.<br><br>
☛ He served as the 11th President of India from 2002 to
2007.<br><br>
☛ Kalam earned a degree in aeronautical engineering from the
Madras
Institute of Technology and in 1958 joined the Defence Research and
Development Organisation (DRDO).<br><br>
☛ In 1969, he moved to the Indian Space Research Organisation,
where
he was project director of the SLV-III, the first satellite launch vehicle
that was
both designed and produced in India.<br><br>
☛ Rejoining DRDO in 1982, Kalam planned the program that
produced
a number of successful missiles, which helped earn him the nickname
<strong>
“Missile Man.” </strong> <br><br>
☛ Among those successes was Agni, India’s first intermediate-range
ballistic missile, which incorporated aspects of the SLV-III and was
launched in
1989. <br><br>
☛ He also played a pivotal organisational, technical, and political role
in
India's Pokhran-II nuclear tests in 1998, the first since the original
nuclear test
by India in 1974. <br><br>
☛ Kalam received <b>7</b> honorary doctorates from <b>40</b>
universities. The Government of India honoured him with the
<b>Padma
Bhushan in 1981</b> and the <b>Padma Vibhushan in 1990</b> for
his work
with ISRO and DRDO and his role as a scientific advisor to the
Government.<br><br>
☛ While delivering a lecture at the Indian Institute of Management
Shillong, Kalam collapsed and died from an apparent cardiac arrest on
<b>27
July 2015</b>, aged 83.<br><br>
☛ Wheeler Island, a national missile test site in Odisha, was renamed
<b>Kalam Island</b> in September 2015.<br><br>
☛ A prominent road in New Delhi was renamed from Aurangzeb
Road
to <b>Dr APJ Abdul Kalam Road</b> in August 2015. <br><br>
☛ In February 2018, scientists from the Botanical Survey of India
named a newly found plant species as Drypetes kalamii, in his
honour.
</p>
</div>
</body>
</html>

mycss.html
.title-APJ, #title {
text-align: center;
}
.tribute-data{
background-color: rgba(55, 242, 255, 0.418);
box-shadow: 20px 20px 20px #40f2ffb6;
font-family: Georgia;
padding: 25px 25px;
margin: 11px;
margin-top: 50px;
}
.title-APJ{
font-size: 35px;
color: white;
text-shadow: 5px 5px 10px black;
}
#title {
color:ivory;
text-shadow: 4px 4px 15px rgba(76, 75, 75, 0.856);
font-size: 40px;
}

OUTPUT:
EX:7 CSS USING LAYOUT

lay=swap');
*{
box-sizing: border-box;
}
body{
font-family: 'Rubik', sans-serif;

.wrapper
{
display: grid;
grid-gap: 5px;
grid-template-columns: 15% 35% 35% 15%;
grid-template-areas:
'header header header header'
'nav nav nav nav'
'side content content ads'
'footer footer footer footer';
}
.main-nav
{
grid-area: nav;
}
.main-nav ul{
display: flex;
list-style: none;
margin: 0;
padding: 0;
background: black;
color:white;
}
.main-nav
a{
display: block;
text-align: center;
font-size: 1.5em;
text-decoration: none;
color:white;
padding: 5px 10px;
}
.main-nav a:hover{
background: #ccc;
}
.main-head{
grid-area: header;
background: blue;
padding: 40px;
font-size: 3em;
text-align: center;}
.content{
grid-area: content;
}
.ads{
grid-area: ads;
background: purple;
min-height: 200px;
}
.side{
grid-area: side;
background: pink;
min-height: 200px;
text-align: center;
}
.main-footer {
grid-area: footer;
background: red;
padding: 40px;
font-size: 3em;
text-align: center;
}
@media (max-width: 600px){
.main-nav ul{
flex-direction: column;
}
.wrapper{
grid-template-columns: auto;
grid-template-areas:
'header'
'nav'
'content'
'side'
'ads'
'footer';
}
}

OUTPUT:

Module:5

Introduction to JavaScript

 JavaScript Can Change HTML Content


 One of many JavaScript HTML methods is getElementById().
 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 accepts both double and single quotes:
Example
document.getElementById('demo').innerHTML = 'Hello JavaScript';
 JavaScript Can Change HTML Attribute Values
 In this example JavaScript changes the value of the src (source)
attribute of an <img> tag:
 JavaScript Can Change HTML Styles (CSS)
 Changing the style of an HTML element, is a variant of
changing an HTML attribute:
Example
document.getElementById("demo").style.fontSize = "35px";
JavaScript Can Hide HTML Elements
Hiding HTML elements can be done by changing the display style:
Example
document.getElementById("demo").style.display = "none";
JavaScript Can Show HTML Elements
Showing hidden HTML elements can also be done by changing the
display style:
Example
document.getElementById("demo").style.display = "block";

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.
 Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by
JavaScript (will not be executed).
This example uses a single-line comment before each code line:
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("myP").innerHTML = "My first
paragraph.";
This example uses a single line comment at the end of each line to
explain the code:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2
 Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to
explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first
paragraph.";

HTML JavaScript
 JavaScript makes HTML pages more dynamic and
interactive.
Example
My First JavaScript

Click me to display date and time


Click me to display Date and Time
 The HTML <script> Tag
 The HTML <script> tag is used to define a client-side
script (JavaScript).
 The <script> element either contains script statements, or
it points to an external script file through the src attribute.
 Common uses for JavaScript are image manipulation, form
validation, and dynamic changes of content.
 To select an HTML element, JavaScript most often uses
the document.getElementById() method.
 This JavaScript example writes "Hello JavaScript!" into an
HTML element with id="demo":
Example
<script>
document.getElementById("demo").innerHTML = "Hello
JavaScript!";
</script>

 The HTML <noscript> Tag


The HTML <noscript> tag defines an alternate content to be
displayed to users that have disabled scripts in their browser or have a
browser that doesn't support scripts:
Example
<script>
document.getElementById("demo").innerHTML = "Hello
JavaScript!";
</script>
<noscript>Sorry, your browser does not support
JavaScript!</noscript>

HTML Script Tags


Tag Description
<script> - Defines a client-side script
<noscript>-Defines an alternate content for users that do not support
client-side scripts

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:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Changing the innerHTML property of an HTML element is a
common way to display data in HTML.

 Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is loaded, will
delete all existing HTML:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try
it</button>
</body>
</html>

JavaScript Variables

Variables are Containers for Storing Data


JavaScript Variables can be declared in 4 ways:
Automatically
Using var
Using let
Using const
In this first example, x, y, and z are undeclared variables.
They are automatically declared when first used:
Example
x = 5;
y = 6;
z = x + y;
Note
It is considered good programming practice to always declare
variables before use.
From the examples you can guess:
x stores the value 5
y stores the value 6
z stores the value 11
Example using var
var x = 5;
var y = 6;
var z = x + y;
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older
browsers.
Example using let
let x = 5;
let y = 6;
let z = x + y;
Example using const
const x = 5;
const y = 6;
const z = x + y;
Mixed Example
const price1 = 5;
const price2 = 6;
let total = price1 + price2;
The two variables price1 and price2 are declared with the const
keyword.
These are constant values and cannot be changed.
The variable total is declared with the let keyword.
The value total can be changed.
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and
Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.
Just Like Algebra
Just like in algebra, variables hold values:
let x = 5;
let y = 6;
Just like in algebra, variables are used in expressions:
let z = x + y;
From the example above, you can guess that the total is calculated to
be 11.

Note:Variables are containers for storing values.

JavaScript Identifier

All JavaScript variables must be identified with unique names.


These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
The general rules for constructing names for variables (unique
identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter.
Names can also begin with $ and _ (but we will not use it in this
tutorial).
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.
Note
JavaScript identifiers are case-sensitive.
 The Assignment Operator
In JavaScript, the equal sign (=) is an "assignment" operator, not an
"equal to" operator.
This is different from algebra. The following does not make sense in
algebra:
x=x+5
In JavaScript, however, it makes perfect sense: it assigns the value of
x + 5 to x.
(It calculates the value of x + 5 and puts the result into x. The value of
x is incremented by 5.)
Note:The "equal to" operator is written like == in JavaScript.
JavaScript Data Types
JavaScript variables can hold numbers like 100 and text values like
"John Doe".
In programming, text values are called text strings
JavaScript can handle many types of data, but for now, just think of
numbers and strings.
Strings are written inside double or single quotes. Numbers are
written without quotes.
If you put a number in quotes, it will be treated as a text string.
Example
const pi = 3.14;
let person = "John Doe";
let answer = 'Yes I am!';
Declaring a JavaScript Variable
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var or the let keyword:
var carName;
or:
let carName;
After the declaration, the variable has no value (technically it is
undefined).
To assign a value to the variable, use the equal sign:
carName = "Volvo";
You can also assign a value to the variable when you declare it:
let carName = "Volvo";
In the example below, we create a variable called carName and assign
the value "Volvo" to it.
Then we "output" the value inside an HTML paragraph with
id="demo":
Example
<p id="demo"></p>
<script>
let carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
Note:It's a good programming practice to declare all variables at the
beginning of a script.
One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with let and separate the variables by comma:
Example
let person = "John Doe", carName = "Volvo", price = 200;
A declaration can span multiple lines:
Example
let person = "John Doe",
carName = "Volvo",
price = 200;
Value = undefined
In computer programs, variables are often declared without a value.
The value can be something that has to be calculated, or something
that will be provided later, like user input.
A variable declared without a value will have the value undefined.
The variable carName will have the value undefined after the
execution of this statement:

Example
let carName;
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable declared with var, it will not
lose its value.
The variable carName will still have the value "Volvo" after the
execution of these statements:
Example
var carName = "Volvo";
var carName;
Note:You cannot re-declare a variable declared with let or const.
let carName = "Volvo";
let carName;
 JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables,
using operators like = and +:
Example
let x = 5 + 2 + 3;
You can also add strings, but strings will be concatenated:
Example
let x = "John" + " " + "Doe";
Example
let x = "5" + 2 + 3;
Note:If you put a number in quotes, the rest of the numbers will be
treated as strings, and concatenated.
Example
let x = 2 + 3 + "5";
 JavaScript Dollar Sign $
Since JavaScript treats a dollar sign as a letter, identifiers containing $
are valid variable names:
Example
let $ = "Hello World";
let $$$ = 2;
let $myMoney = 5;

Using the dollar sign is not very common in JavaScript, but


professional programmers often use it as an alias for the main
function in a JavaScript library.
In the JavaScript library jQuery, for instance, the main function $ is
used to select HTML elements. In jQuery $("p"); means "select all p
elements".

 JavaScript Underscore (_)


Since JavaScript treats underscore as a letter, identifiers containing _
are valid variable names:
Example
let _lastName = "Johnson";
let _x = 2;
let _100 = 5;
Using the underscore is not very common in JavaScript, but a
convention among professional programmers is to use it as an alias
for "private (hidden)" variables.
Exercise:
Create a variable called carName and assign the value Volvo to it.
let
="
";

JavaScript Data Types


JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

 The Object Datatype


The object data type can contain:

1. An object
2. An array
3. A date

Examples
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");

The Concept of Data Types

In programming, data types is an important concept.


To be able to operate on variables, it is important to know something
about the type.
Without data types, a computer cannot safely solve this:
let x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an
error or will it produce a result?
JavaScript will treat the example above as:
let x = "16" + "Volvo";
Note: When adding a number and a string, JavaScript will treat the
number as a string.
Example
let x = 16 + "Volvo";
Example
let x = "Volvo" + 16;
JavaScript evaluates expressions from left to right. Different
sequences can produce different results:
JavaScript:
let x = 16 + 4 + "Volvo";
Result:
20Volvo
JavaScript:
let x = "Volvo" + 16 + 4;
Result:
Volvo164
In the first example, JavaScript treats 16 and 4 as numbers, until it
reaches "Volvo".
In the second example, since the first operand is a string, all operands
are treated as strings.

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can
be used to hold different data types:
Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
Example
// Using double quotes:
let carName1 = "Volvo XC60";
// Using single quotes:
let carName2 = 'Volvo XC60';
You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:
Example
// Single quote inside double quotes:
let answer1 = "It's alright";
// Single quotes inside double quotes:
let answer2 = "He is called 'Johnny'";
// Double quotes inside single quotes:
let answer3 = 'He is called "Johnny"';
You will learn more about strings later in this tutorial.

JavaScript Numbers
All JavaScript numbers are stored as decimal numbers (floating
point).
Numbers can be written with, or without decimals:
Example
// With decimals:
let x1 = 34.00;
// Without decimals:
let x2 = 34;
Exponential Notation
Extra large or extra small numbers can be written with scientific
(exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
Note
Most programming languages have many number types:
Whole numbers (integers):
byte (8-bit), short (16-bit), int (32-bit), long (64-bit)
Real numbers (floating-point):
float (32-bit), double (64-bit).
Javascript numbers are always one type:
double (64-bit floating point).
You will learn more about numbers later in this tutorial.

 JavaScript BigInt
All JavaScript numbers are stored in a a 64-bit floating-point format.
JavaScript BigInt is a new datatype (ES2020) that can be used to store
integer values that are too big to be represented by a normal

 JavaScript Number.
Example
let x = BigInt("123456789012345678901234567890");
You will learn more about BigInt later in this tutorial.

 JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
Booleans are often used in conditional testing.
You will learn more about booleans later in this tutorial.

JavaScript Arrays
 JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing
three items (car names):
Example
const cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0],
second is [1], and so on.
You will learn more about arrays later in this tutorial.

 JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by
commas.
Example
const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName,
lastName, age, and eyeColor.
You will learn more about objects later in this tutorial.

The type of Operator


You can use the JavaScript typeof operator to find the type of a
JavaScript variable.
The typeof operator returns the type of a variable or an expression:

Example
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof "John Doe" // Returns "string"
Example
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
You will learn more about typeof later in this tutorial.

Undefined
In JavaScript, a variable without a value, has the value undefined. The
type is also undefined.
Example
let car; // Value is undefined, type is undefined
Example
car = undefined; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
Example
let car = ""; // The value is "", the typeof is "string"
Test Yourself With Exercises
Exercise:
Use comments to describe the correct data type of the following
variables:
let length = 16;
let lastName = "Johnson";
const x = {
firstName: "John",
lastName: "Doe"
};

JavaScript Array Methods


Array length
Array toString()
Array pop()
Array push()
Array shift()
Array unshift()
Array join()
Array delete()
Array concat()
Array flat()
Array splice()
Array slice()
The methods are listed in the order they appear in this tutorial page
 JavaScript Array length
The length property returns the length (size) of an array:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
 JavaScript Array toString()
The JavaScript method toString() converts an array to a string of
(comma separated) array values.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the
separator:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
Result:
Banana * Orange * Apple * Mango
Module:7

JavaScript DOM Introduction to dynamic &interaction web page


content

HTML DOM
 With the HTML DOM, JavaScript can access and change all the
elements of an HTML document.
 The HTML DOM (Document Object Model)
 When a web page is loaded, the browser creates a Document
Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:


The HTML DOM Tree of Objects
 DOM HTML tree
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
 JavaScript can change all the HTML elements in the page
 JavaScript can change all the HTML attributes in the page
 JavaScript can change all the CSS styles in the page
 JavaScript can remove existing HTML elements and attributes
 JavaScript can add new HTML elements and attributes
 JavaScript can react to all existing HTML events in the page
 JavaScript can create new HTML events in the page

Example:
<!doctype html>
<html>
<head>
<title>JavaScript</title>
<style>h1{text-align: center;}</style>
</head>
<body>
<h1 id="message">Welcome to JavaScript</h1>
<input name="message">
<button>Click Me</button>
<ul><li class="highlight">One</li><li>Two</li><li
class="highlight">Three</li><li>Four</li></ul>
<div><span class="highlight">Welcome</span> to the JavaScript
DOM. All Elements on this page are objects. <span
class="highlight">Page</span> Elements have properties and
methods accessed <span class="highlight">by JavaScript</span>
</div>
<script src="script.js"></script>
</body>
</html>
JavaScript

const message = document.getElementById('message');


console.log(message);
const listItems = document.getElementsByTagName('li');
console.log(listItems);
const highlights = document.getElementsByClassName('highlight');
console.log(highlights);
const val1 = document.querySelector('li');
console.log(val1);
const val2 = document.querySelector('#message');
console.log(val2);
const val3 = document.querySelector('.highlight');
console.log(val3);

OUTPUT:
Module:8
JavaScript advanced coding

 JavaScript Number Methods

These number methods can be used on all JavaScript numbers:

Method Description
toString() Returns a number as a string
toExponential() Returns a number written in exponential notation
toFixed() Returns a number written with a number of decimals
toPrecision() Returns a number written with a specified length
ValueOf() Returns a number as a number

The toString() Method


 The toString() method returns a number as a string.
 All number methods can be used on any type of numbers
(literals, variables, or expressions):
Example
let x = 123;
x.toString();
(123).toString();
(100 + 23).toString();

The toExponential() Method


 toExponential() returns a string, with a number rounded and
written using exponential notation.
 A parameter defines the number of characters behind the
decimal point:
Example
let x = 9.656;
x.toExponential(2);
x.toExponential(4);
x.toExponential(6);

JavaScript String Methods


String length
String slice()
String substring()
String substr()
String replace()
String replaceAll()
String toUpperCase()
String toLowerCase()
String concat()
String trim()
String trimStart()
String trimEnd()
String padStart()
String padEnd()
String charAt()
String charCodeAt()
String split()

JavaScript String Length


The length property returns the length of a string:
Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

Extracting String Parts


There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)

JavaScript String slice()


slice() extracts a part of a string and returns the extracted part in a new
string.
The method takes 2 parameters: start position, and end position (end
not included).
Example
Slice out a portion of a string from position 7 to position 13:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
Examples
let text = "Apple, Banana, Kiwi";
let part = text.slice(7);
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12, -6);
JavaScript String substring()

substring() is similar to slice().


The difference is that start and end values less than 0 are treated as 0
in substring().
Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);

JavaScript String substr()


substr() is similar to slice().
The difference is that the second parameter specifies the length of the
extracted part.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
If the first parameter is negative, the position counts from the end of
the string.
Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);

Replacing String Content


The replace() method replaces a specified value with another value in
a string:
Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

String ReplaceAll()
In 2021, JavaScript introduced the string method replaceAll():
Example
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
The replaceAll() method allows you to specify a regular expression
instead of a string to be replaced.

If the parameter is a regular expression, the global flag (g) must be


set, otherwise a TypeError is thrown.
Example
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

Converting to Upper and Lower Case


A string is converted to upper case with toUpperCase():
A string is converted to lower case with toLowerCase():

JavaScript String toUpperCase()


Example
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
JavaScript String toLowerCase()
Example
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to lower

JavaScript String concat()


concat() joins two or more strings:
Example
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
The concat() method can be used instead of the plus operator. These
two lines do the same:
Example
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");
Formally said:
Strings are immutable: Strings cannot be changed, only replaced.

JavaScript String trim()

The trim() method removes whitespace from both sides of a string:


Example
let text1 = " Hello World! ";
let text2 = text1.trim();

JavaScript String trimStart()


ECMAScript 2019 added the String method trimStart() to JavaScript.
The trimStart() method works like trim(), but removes whitespace
only from the start of a string.
Example
let text1 = " Hello World! ";
let text2 = text1.trimStart();

JavaScript String trimEnd()


ECMAScript 2019 added the string method trimEnd() to JavaScript.
The trimEnd() method works like trim(), but removes whitespace only
from the end of a string.
Example
let text1 = " Hello World! ";
let text2 = text1.trimEnd();

Script String Padding


ECMAScript 2017 added two new string methods to JavaScript:
padStart() and padEnd() to support padding at the beginning and at
the end of a string.

JavaScript String padStart()


The padStart() method pads a string from the start.
It pads a string with another string (multiple times) until it reaches a
given length.
Examples
Pad a string with "0" until it reaches the length 4:
let text = "5";
let padded = text.padStart(4,"0");
Pad a string with "x" until it reaches the length 4:
let text = "5";
let padded = text.padStart(4,"x");
JavaScript String padEnd()
The padEnd() method pads a string from the end.
It pads a string with another string (multiple times) until it reaches a
given length.

Examples
let text = "5";
let padded = text.padEnd(4,"0");
let text = "5";
let padded = text.padEnd(4,"x");

Extracting String Characters


There are 3 methods for extracting string characters:
charAt(position)
charCodeAt(position)
Property access [ ]

JavaScript String charAt()


The charAt() method returns the character at a specified index
(position) in a string:
Example
let text = "HELLO WORLD";
let char = text.charAt(0);
JavaScript String charCodeAt()
The charCodeAt() method returns the unicode of the character at a
specified index in a string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
Example
let text = "HELLO WORLD";
let char = text[0];

JavaScript String split()


A string can be converted to an array with the split() method:
Example
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
If the separator is omitted, the returned array will contain the whole
string in index [0].
If the separator is "", the returned array will be an array of single
characters:
Example
text.split("")

JavaScript Math Object

The JavaScript Math object allows you to perform mathematical tasks


on numbers.
Example
Math.PI;
The Math Object
Unlike other objects, the Math object has no constructor.
The Math object is static.
All methods and properties can be used without creating a Math
object first.

Math Properties (Constants)

The syntax for any Math property is : Math.property.


JavaScript provides 8 mathematical constants that can be accessed as
Math properties:
Example
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E

Math Methods
The syntax for Math any methods is : Math.method(number)

Number to Integer
There are 4 common methods to round a number to an integer:
Math.round(x) Returns x rounded to its nearest integer
Math.ceil(x) Returns x rounded up to its nearest integer
Math.floor(x) Returns x rounded down to its nearest integer
Math.trunc(x) Returns the integer part of x (new in ES6)
Math.round()
Math.round(x) returns the nearest integer:
Examples
Math.round(4.6);
Math.round(4.5);
Math.round(4.4);
Math.ceil()
Math.ceil(x) returns the value of x rounded up to its nearest integer:
Example
Math.ceil(4.9);
Math.ceil(4.7);
Math.ceil(4.4);
Math.ceil(4.2);
Math.ceil(-4.2);
Math.floor()
Math.floor(x) returns the value of x rounded down to its nearest
integer:
Example
Math.floor(4.9);
Math.floor(4.7);
Math.floor(4.4);
Math.floor(4.2);
Math.floor(-4.2);
Math.trunc()
Math.trunc(x) returns the integer part of x:
Example
Math.trunc(4.9);
Math.trunc(4.7);
Math.trunc(4.4);
Math.trunc(4.2);
Math.trunc(-4.2);
Math.sign()
Math.sign(x) returns if x is negative, null or positive:
Example
Math.sign(-4);
Math.sign(0);
Math.sign(4);
Math.trunc() and Math.sign() were added to JavaScript 2015 - ES6.

Math.pow()
Math.pow(x, y) returns the value of x to the power of y:
Example
Math.pow(8, 2);
Math.sqrt()
Math.sqrt(x) returns the square root of x:
Example
Math.sqrt(64);
Math.abs()
Math.abs(x) returns the absolute (positive) value of x:
Example
Math.abs(-4.7);
Math.sin()
Math.sin(x) returns the sine (a value between -1 and 1) of the angle x
(given in radians).
If you want to use degrees instead of radians, you have to convert
degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
Example
Math.sin(90 * Math.PI / 180); // returns 1 (the sine of 90 degrees)

Math.cos()
Math.cos(x) returns the cosine (a value between -1 and 1) of the angle
x (given in radians).
If you want to use degrees instead of radians, you have to convert
degrees to radians:
Angle in radians = Angle in degrees x PI / 180.
Example
Math.cos(0 * Math.PI / 180); // returns 1 (the cos of 0 degrees)
Math.min() and Math.max()
Math.min() and Math.max() can be used to find the lowest or highest
value in a list of arguments:
Example
Math.min(0, 150, 30, 20, -8, -200);
Example
Math.max(0, 150, 30, 20, -8, -200);

Math.random()
Math.random() returns a random number between 0 (inclusive), and 1
(exclusive):
Example
Math.random();
You will learn more about Math.random() in the next chapter of this
tutorial.
The Math.log() Method
Math.log(x) returns the natural logarithm of x.
The natural logarithm returns the time needed to reach a certain level
of growth:
Examples
Math.log(1);
Math.log(2);
Math.log(3);
Math.E and Math.log() are twins.

How many times must we multiply Math.E to get 10?


Math.log(10);
The Math.log2() Method
Math.log2(x) returns the base 2 logarithm of x.
How many times must we multiply 2 to get 8?
Math.log2(8);
The Math.log10() Method
Math.log10(x) returns the base 10 logarithm of x.
How many times must we multiply 10 to get 1000?
Math.log10(1000);

JavaScript Object Prototypes


All JavaScript objects inherit properties and methods from a
prototype.
In the previous chapter we learned how to use an object constructor:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
We also learned that you can not add a new property to an existing
object constructor:
Example
Person.nationality = "English";
To add a new property to a constructor, you must add it to the
constructor function:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}

Prototype Inheritance
All JavaScript objects inherit properties and methods from a
prototype:
Date objects inherit from Date.prototype
Array objects inherit from Array.prototype
Person objects inherit from Person.prototype
The Object.prototype is on the top of the prototype inheritance chain:
Date objects, Array objects, and Person objects inherit from
Object.prototype.
Adding Properties and Methods to Objects
Sometimes you want to add new properties (or methods) to all
existing objects of a given type.
Sometimes you want to add new properties (or methods) to an object
constructor.

Using the prototype Property


The JavaScript prototype property allows you to add new properties
to object constructors:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";

The JavaScript prototype property also allows you to add new


methods to objects constructors:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};

Module:9
Coding exercise with JavaScript

HTML DOM Document createElement()


Examples
Create a <p> element and append it to the document:
const para = document.createElement("p");
para.innerText = "This is a paragraph";
document.body.appendChild(para);
Create a <p> element and append it to an element:
const para = document.createElement("p");
para.innerHTML = "This is a paragraph.";
document.getElementById("myDIV").appendChild(para);

The Element insertBefore() Method


Syntax
document.createElement(type)
Parameters
Parameter Description
type Required.
The type of element to create.
Return Value
Type Description
Node The created element node.
More Examples
Create a button:
const btn = document.createElement("button");
btn.innerHTML = "Hello Button";
document.body.appendChild(btn);

JavaScript Closure
A closure in JavaScript is a function that has access to the variables
in its parent scope, even after the parent function has completed
execution.
This allows for data to be "closed over" or remembered by the inner
function, even after the outer function has returned.
For example: function makeCounter() { let count = 0; return
function() {
return count++; } }let counter = makeCounter();
console.log(counter()); // outputs 0 console.log(counter()); // outputs 1
console.log(counter()); // outputs 2
Here, the makeCounter function returns an inner function that has
access to the count variable declared in its parent scope, and can
"remember" the current count value even after the function has
completed execution. Each time the inner function is called, it returns
the current value of count and increments it by
1. const a = 'hello';
console.log(a); abc(); function abc(){ //const a = 'world';
console.log(a); }function myCount(){ let count = 0; return function(){
return count++; } }function myCount2(){ let count = 0 ; return count+
+; }let cnt = myCount(); let cnt2 = myCount2; for(let x=0;x<10;x++){
console.log(cnt());
console.log(cnt2()); }
JavaScript Closure Advanced

In this example, the makeAdder function takes in a single argument x


and returns an inner function that takes in a second argument y.
The inner function has access to the x variable declared in the parent
scope and uses it to add x and y together and return the result.
We can see here that the outer function makeAdder has been executed
twice and it returns two different inner functions which are assigned
to different variables add5 and add10 and these inner functions are
able to remember their respective parent scope values of x.
function makeAdder(x) { return function(y) { return x + y; } }let add5
= makeAdder(5); console.log(add5(3)); // outputs 8
console.log(add5(4)); // outputs 9 let add10 = makeAdder(10);
console.log(add10(5)); // outputs 15 console.log(add10(6));
// outputs 16
const output = document.querySelector('#output');
function adder(val){ return function(val2){ return val + val2; }
}let a1 = adder(15); console.log(a1(2)); for(let x=0;x<10;x++)
{ output.innerHTML += `<div>
Output ${(a1(2+x))}</div>`;}

JavaScript Image Gallery and Dynamic Image Gallery


JavaScript Image Gallery and Dynamic Image Gallery using page
classes or create page elements on the fly with code
Here is an example of a JavaScript image gallery maker that creates a
simple image gallery with prev/next buttons to navigate through the
images: <div id="gallery"> <img src="image1.jpg" id="current-
image"> <button id="prev-button">Prev</button> <button id="next-
button">Next</button> </div> <script> var images = ["image1.jpg",
"image2.jpg", "image3.jpg", "image4.jpg"]; var currentIndex = 0; var
gallery = document.getElementById("gallery"); var currentImage =
document.getElementById("current-image"); var prevButton =
document.getElementById("prev-button");
var nextButton = document.getElementById("next-button");
prevButton.addEventListener("click", function() { currentIndex--; if
(currentIndex < 0) { currentIndex = images.length -
1; }currentImage.src = images[currentIndex]; });
nextButton.addEventListener("click", function() { currentIndex++; if
(currentIndex >= images.length) { currentIndex =
0; }currentImage.src = images[currentIndex]; }); </script>

This example uses JavaScript to select the elements from the HTML,
and add event listeners to the prev/next buttons to navigate through
the images in the images array when clicked.
The currentIndex variable keeps track of the current image being
displayed, and the currentImage.src property is updated to show the
next/prev image in the array when the buttons are clicked.
The above code is an example of a JavaScript image gallery maker
that creates a simple image gallery with prev/next buttons.
The code uses JavaScript to select the necessary elements from the
HTML, such as the gallery container, current image, and prev/next
buttons. It then adds event listeners to the
prev/next buttons, so that when they are clicked, the current image
being displayed is updated to the next/prev image in the images array.
The currentIndex variable keeps track of the current image being
displayed, and it is updated each time the prev/next buttons are
clicked.
When the current index reaches the end of the images array, it resets
to the first image, thus creating an infinite loop.
Dynamic Image Gallery How to Create an Image Gallery and
Dynamic Image Gallery with JavaScript Code The image gallery can
also be used within a function to create multiple image galleries all
working independently.
Either creating them on the fly within the code or selecting existing
elements with the class name and generating images within those
elements.
const output = document.querySelector('.output');
const images = ['one.jpg','two.jpg','three.jpg','four.jpg']; /*for(let
x=0;x<12;x++){ const el = document.createElement('div');
output.append(el); cGallery(el); }

*/const eles = document.querySelectorAll('.gal');


eles.forEach(el => { cGallery(el); })function cGallery(parentEle)
{ let curIndex = 0; const gallery = document.createElement('div');
const curImage = document.createElement('img');
curImage.setAttribute('src','one.jpg');
const btn1 = document.createElement('button');
btn1.textContent = 'Prev'; const btn2 =
document.createElement('button'); btn2.textContent = 'Next';
parentEle.append(gallery);
gallery.append(curImage);
gallery.append(btn1); gallery.append(btn2);
btn1.addEventListener('click',()=>{ curIndex--; if(curIndex<0)
{ curIndex = images.length-1;
}console.log(images[curIndex]); curImage.src =
images[curIndex]; })btn2.addEventListener('click',()=>{ curIndex++;
if(curIndex >= images.length){ curIndex =
0; }console.log(images[curIndex]); curImage.src =
images[curIndex]; }) }

Module:10
Simple web site from starch
Build a Website
Create a Website with a CSS Framework
 Start Page Template
Ever heard about W3Schools Spaces? Here you can create your
website from scratch or use a template.
* no credit card required

 A "Layout Draft"
It is always wise to draw a layout draft of the page design before
building a website.
Having a "Layout Draft" will make it a lot easier to create a web site:

 Doctype, Meta Tags, and CSS


The doctype should define the page as an HTML5 document:
<!DOCTYPE html>
A meta tag should define the character set to be UTF-8:
<meta charset="UTF-8">
A viewport meta tag should make the web site work on all devices
and screen resolutions:
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet"
href="https://www.w3schools.com/w3css/3/w3.css">
Our first empty web page will look much like this:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="stylesheet"
href="https://www.w3schools.com/w3css/3/w3.css">
<body>
<!-- Content will go here -->

</body>
</html>

Creating Page Content


Inside the <body> element of our web site we will use our "Layout
Picture" and create:
 A navigation bar
 A slide show
 A header
 Some sections and articles
 A footer
Semantic Elements
HTML5 introduced several new semantic elements. Semantic
elements are important to use because they define the structure of web
pages and helps screen readers and search engines to read the page
correctly.
These are some of the most common semantic HTML elements:
The <section> element can be used to define a part of a website with
related content.
The <article> element can be used to define an individual piece of
content.
The <header> element can be used to define a header (in a document,
a section, or an article).
The <footer> element can be used to define a footer (in a document, a
section, or an article).
The <nav> element can be used to define a container of navigation
links.
However, it is up to you if you want to use <div> elements instead.
The Navigation Bar
On our "Layout Draft" we have a "Navigation bar".
<!-- Navigation -->
<nav class="w3-bar w3-black">
<a href="#home" class="w3-button w3-bar-item">Home</a>
<a href="#band" class="w3-button w3-bar-item">Band</a>
<a href="#tour" class="w3-button w3-bar-item">Tour</a>
<a href="#contact" class="w3-button w3-bar-item">Contact</a>
</nav>

We can use a <nav> or <div> element as a container for the


navigation links.
The w3-bar class is a container for navigation links.
The w3-black class defines the color of the navigation bar.
The w3-bar-item and w3-button class styles the navigation links
inside the bar.

Module:11

HTTP request in Javascript Get JSON data with xhr method and fetch
methods HTTP request in Javascript? There are several ways to make
an HTTP request in JavaScript, including using the XMLHttpRequest
object or the fetch() function.
Here is an example of making an HTTP GET request using
XMLHttpRequest: var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com");
xhr.send(); Here's an example of making an HTTP GET request to a
JSON endpoint using the XMLHttpRequest object and parsing the
response as JSON: var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/data.json"); xhr.onload =
function() { if (xhr.status === 200) { var data =
JSON.parse(xhr.responseText); console.log(data); } else
{ console.error(xhr.statusText); } };xhr.onerror = function()
{ console.error(xhr.statusText); };xhr.send(); In this example, a new
XMLHttpRequest object is created, and then opened with the "GET"
method and the specified JSON endpoint URL. The onload event is
used to handle the response, and onerror event is used to handle any
error. The xhr.status is checked and if it's 200, it indicates that the
request is successful, then we parse the response as JSON and log the
data to the console. If the xhr.status is not 200, it means there's an
error and it logs the error message in the onerror function. If there's
any network error, the onerror function is triggered, and it logs the
error message. Finally the request is sent using the xhr.send() method.

Please note that you should always check the response status code and
handle it accordingly. Also, XMLHttpRequest is an old API, and
fetch() is more modern and recommended The fetch() method is a
modern JavaScript method that allows you to make HTTP requests,
similar to the XMLHttpRequest object.
The fetch() method returns a promise that resolves to the response of
the request, which can be a Response or Error object. When you call
the fetch() method, you pass in the URL of the endpoint you want to
make the request to.
Module:12

You can also pass in an options object as the second parameter, which
allows you to configure the request, such as setting the HTTP method,
headers, and body.
The fetch() method returns a promise that resolves to the response of
the request. Once you have the response, you can use
the .json(), .text(), .blob() methods, etc to access the data of the
response. Here's an example of how you can use the fetch() method:
fetch("https://example.com/data.json") .then(response =>
response.json()) .then(data => console.log(data)) .catch(error =>
console.log(error)); In this example, the fetch() method is used to
make a GET request to a JSON endpoint. The .then() method is used
to handle the response, which is passed as a parameter to the first
callback function. The response.json() method is used to parse the
response as JSON and the result is passed to the second callback
function.
Finally, the data is logged to the console. If there's anyerror during
the request, it will be caught and logged by the catch function.
The fetch() method is a more modern and recommended way to make
HTTP requests in JavaScript, it's more concise and easy to use, and
it's supported in most modern browsers. And here is an example of
making an

HTTP GET request using fetch():


fetch("https://example.com") .then(response =>
response.text()) .then(data => console.log(data)) .catch(error =>
console.log(error));
The first example uses the XMLHttpRequest object to create a new
request, open it with the "GET" method and the specified URL, and
then send it.
The response to the request can then be handled using the onload or
onerror events.
The second example uses the fetch() function to make the same GET
request to the specified URL, and then uses the .then() method to
handle the response, which is passed as a parameter to the first
callback function.
The response is transformed to text and then logged in the second
callback function.
If there's any error during the request, it will be caught and logged by
the catch function.
Here's an example of making an HTTP GET request to a JSON
endpoint using the fetch() function and parsing the response as JSON:
fetch("https://example.com/data.json")
.then(response => response.json()) .then(data =>
console.log(data)) .catch(error => console.log(error)); The fetch()
function is used to make the GET request to the specified JSON
endpoint. The response.json() method is then used to parse the
response as JSON and the result is passed to the first callback
function. In the second callback function, the data is logged. If there's
any error during the request, it will be caught and logged by the catch
function. const output = document.querySelector('.output'); const url =
'https://www.discoveryvip.com/shared/person1000.json'; const xhr =
new XMLHttpRequest(); xhr.open('GET',url); xhr.onload = function()
{

if(xhr.status === 200){ const data = JSON.parse(xhr.responseText);


maker(data); }else{console.error(xhr.statusText); } }xhr.onerror =
function(){ console.error(xhr.statusText); }xhr.send();
output.innerHTML += '<hr>'; fetch(url) .then(res =>
res.json()) .then(data => maker(data)) .catch(error =>
console.log(error)); function maker(data){ data.forEach(ele
=>{ output.innerHTML += ` <div>${ele.name.first} ${ele.name.last}
${ele.age}</div>

<small>${JSON.stringify(ele)}</small>`; })output.innerHTML +=
'<hr>'; }JSON Code [ { "name": { "first": "Laurence", "last": "Svekis"
},"age": 40, "location": { "city": "Toronto", "country": "Canada" } },{
"name": { "first": "Lisa", "last": "Suekis" },"age": 30,
"location": { "city": "New York", "country": "USA" } },{ "name":
{ "first": "Johyn", "last": "Sekis" },"age": 50, "location": { "city":
"New York", "country": "USA" } } ]How to add Fade Out and Fade
in to page elements pure JavaScript Learn how to apply fade in and
fade out effects to HTML page elements with pure JavaScript code.
Select and create new page elements dynamically with code, add
event listeners and have the page elements fade in and fade out once
the event is triggered. Adding Fade Effects to new and existing Page
Elements
const output = document.querySelector('#output'); for(let x=0;x<5;x+
+){ const el = document.createElement('div'); output.append(el);
const btn = document.createElement('button'); btn.textContent =
`Click Me ${x}`; el.append(btn); const div =
document.createElement('div');

div.style.transition = 'opacity 1500ms'; div.style.opacity = '1';


div.textContent = `Counter ${x+1}`; el.append(div);
btn.addEventListener('click',()=>{ if(div.style.opacity === '1')
{ div.style.opacity = '0'; }else{div.style.opacity = '1'; } }) }const
fademe = document.querySelectorAll('.fader');
fademe.forEach((ele)=>{ ele.style.transition = 'opacity 500ms';

ele.style.opacity = '1'; ele.addEventListener('click',


(e)=>{ ele.style.opacity = '0'; }) }) <div id="output">Complete
JavaScript Course </div> <div class="fader">One</div> <div
class="fader">Two</div> <div class="fader">Three</div> <div
class="fader">Four</div> <script src="app1.js"></script> How to

module:13
Create page HTML elements with JavaScript code append prepend
before after pure JavaScript How to append and add new page
elements with JavaScript How to append and add new page elements
with JavaScript using append, appendChild, prepend, before and after
methods to dynamically add and reposition page elements
Laurence Svekis https://basescripts.com/
Create Page elements with Code How to append and add new page
elements with JavaScript

const output = document.querySelector('#output'); const pageBody =


document.body; const el1 = document.createElement('h1');
el1.textContent = 'Hello World 1'; console.log(el1);
pageBody.append(el1); output.append(el1); const res1 =
output.appendChild(el1); console.log(res1); res1.textContent = 'Hello
1'; el1.textContent = 'Hello 2'; output.before(el1); output.after(el1);
output.prepend(el1); const ul = document.createElement('ul');
output.append(ul);

for(let i=0;i<10;i++){ const li1 = document.createElement('li');


li1.textContent = `#${i+1}`; ul.append(li1); }Regex Checking for
Numbers in the input field Check for values that match a Regex
pattern in the input field. Push a button and apply the match checker
to return the results in the console. /^[0-9]*$/g = Only numbers in the
string /[0-9]+/g = Will return numbers in the result ignore non digits
0-9 /[\D]/g = Every Character other than digits /\d/g = Digits
separated

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<div> <input type="text" id="nums">
<button id="btn">Checker</button>
</div>
<script src="app.js">
</script>
</body>
</html>
const nums = document.querySelector('#nums'); const btn =
document.querySelector('#btn'); btn.onclick = ()=>{ const inputValue
= nums.value; const patt = /^[0-3]*$/g; const results =
inputValue.match(patt); console.log(results); const valNum = results !
= null; console.log(valNum); }
JavaScript is a function that has access to variables in its parent scope,
even after the parent function has returned.
Closures are created when a function is defined inside another
function, and the inner function retains access to the variables in the
outer function's scope.
Here is an example of a closure in JavaScript: code example function
outerFunction(x) { var innerVar = 4; function innerFunction() { return
x + innerVar; }return innerFunction; }var closure = outerFunction(2);
console.log(closure()); // Output: 6 In this example, the innerFunction
is a closure because it has access to the variable x and innerVar from
the outerFunction even after outerFunction has returned. A closure
has three scope chains:
1. It has access to its own scope (variables defined between its curly
braces {}).
2. It has access to the outer function's variables.
3. It has access to the global variables. Closures are commonly used
in JavaScript for a variety of tasks, such as:
● Implementing private methods and variables.
● Creating callback functions that retain access to variables from
their parent scope.
● Creating and returning an object that has access to variables from
its parent scope.
JavaScript closures are an important concept and it is important to
understand how closures work in JavaScript. It is also important to be
aware of the scope chain, and how closures interact with the scope
chain.
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<h1>Complete JavaScript Course </h1>
<div class="output"></div>
<script src="app6.js"></script>
</body>
</html>
const val1 = 10;
function outerFun(x){
const val2 = 10;
function innerFun(){
Laurence Svekis https://basescripts.com/
return x + val2 + val1; }
return innerFun; }
const val3 = outerFun(15);
console.log(val3());
for(let x=0;x<10;x++){
console.log(outerFun(x+2)());
}
Module:14
Web design and web development resources and helpful tips and
lesson
Github and gitpages getting started with GitHub and git

Git and GitHub Pages Quick Setup Guide


Go to https://github.com/ and create an account. Then setup a new
repository. Click the Green Code button in the drop down menu to get
the
HTTPS URL for the repo. You will need this to clone the repo to your
localmachine
Open your editor, I am using https://code.visualstudio.com/ which
comes
with a built-in terminal making it easy to connect to GitHub. Create a
folder
to organize your files, download and install git on your machine. To
check if
git is on your local machine type git –status which should return the
version
of git on your machine. If not go to
https://www.git-scm.com/downloads
and download the necessary setup files for git.
To clone your repo use the git command with your URL
git clone https://github.com/svekis1/myPages.git
No change directory (cd) to the directory of your git repo on your
local
machine. Using ls/dir to check to ensure you are in the correct folder
in the
terminal.
Now create an index.html file that will serve as your landing page for
the
gitPages. Update and setup your HTML for the gitHub Page.
Once ready add the new updates to the staging environment locally,
using
git status check that files are added. Next commit the files using
commit.
git add --all
git commit -m "Updated"
git push
Course Source Code by Laurence Svekis https://basescripts.com/
Open your github account and check that the files are now updated in
the
repo. Under the settings tab select Pages in the left hand side menu.
Wait a couple minutes for the gitHub page to be setup. The link is
now at
the top of the Pages, page. Click the link to visit the site, any changes
you
make locally now can be pushed to the GitHub repo and they will be
reflected shortly on your GitHub Page
Ex:8 BASIC JAVASCRIPT PROGRAM

HTML
<!doctype html>
<html>
<head>
<title>JavaScript</title>
<style>h1{text-align: center;}</style>
</head>
<body>
<h1>Welcome to JavaScript</h1>
<button onclick='alert("hi");'>Click Me</button>
<script src="script.js"></script>
</body>
</html>
JavaScript
alert('hello');
OUTPUT:
Ex:9 JAVASCRIPT USING QUERY SELECTOR

<!doctype html>
<html>
<head>
<title>Example querySelectorAll</title>
</head>
<body>
<ul></ul>
<input type="text" name="myInput" value="test">
<button>Click Me to add item</button>
<script>
const ul = document.querySelector('ul');
const li = document.querySelectorAll('li');
const myInput = document.querySelector('input[name="myInput"]');
const btn = document.querySelector('button');
let x = 0;
let val = myInput.value;
btn.addEventListener('click', (e) => {
//console.log(e);
x++;
e.target.textContent = 'Clicked ' + x;
addListItem();
})

function addListItem() {
//console.log(myInput.value);
//console.log(val);
console.dir(ul);
console.log(ul.children.length);
console.log(ul.childElementCount);
const lis = document.querySelectorAll('li');
//console.log(lis.length);

if (myInput.value.length > 3 && lis.length < 5) {


const li = document.createElement('li');
li.textContent = myInput.value;
const val1 = ul.appendChild(li);
//console.log(val1);
}

}
</script>
</body>
</html>
OUTPUT:
Ex:10 JAVASCRIPT WITH STICKY NAVBAR

HTML
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<title>Single Page Site Sticky Navbar Bottom</title>
<link rel="stylesheet" href="style.css"> </head>

<body>
<div id="navbar">
<nav> <a href="#home" class="active">Home</a> <a
href="#about">About</a> <a href="#products">Products</a> <a
href="#contact">Contact</a> </nav>
</div>
<div id="wrapper">
<header>
<div>
<h2>Welcome to my Website</h2>
<p>Content</p>
</div>
</header>
<section id="home">
<article>
<h2>Home</h2>
<p><strong>Pellentesque habitant morbi tristique</strong>
senectus et netus et malesuada fames ac turpis egestas. Vestibulum
tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec
eu libero sit amet quam egestas semper. <em>Aenean ultricies mi
vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et
sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed,
<code>commodo vitae</code>, ornare sit amet, wisi. Aenean
fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a>
in turpis pulvinar facilisis. Ut felis.</p>
</article>
</section>
<section id="about">
<article>
<h2>About</h2>
<p>Pellentesque habitant morbi tristique senectus et netus et
malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat
vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet
quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat
eleifend leo.</p>
</article>
</section>
<section id="products">
<article>
<h2>Products</h2>
<ul>
<li><img src="birds.png">
<p>My Birds</p>
</li>
<li><img src="img1.png">
<p>My Image 1</p>
</li>
<li><img src="img2.png">
<p>My Image 2</p>
</li>
<li><img src="img3.png">
<p>My Image 3</p>
</li>
</ul>
</article>
</section>
<section id="contact">
<article>
<h2>Contact</h2>
<form>
<div class="row">
<label for="name">Name:</label>
<input type="text" name="name" placeholder="Your Name">
</div>
<div class="row">
<label for="name">Email:</label>
<input type="email" name="email" placeholder="Your
Email"> </div>
<div class="row">
<button type="submit">Send Email</button>
</div>
</form>
</article>
</section>
</div>
<footer id="footer">
<div>&copy; Copyright 2020 more company info.</div>
</footer>
</body>

</html>

CSS

/*
CSS HEX
--onyx: #393e41;
--timberwolf: #d3d0cb;
--platinum: #e7e5df;
--keppel: #44bba4;
--maize-crayola: #e7bb41;
*/

@import url('https://fonts.googleapis.com/css2?
family=Roboto+Slab&display=swap');
*{
box-sizing: border-box;
}
body,
html {
height: 100vh;
font-family: 'Roboto Slab', serif;
}

a{
text-decoration: none;
color: #44bba4;
}

a:hover {
text-decoration: none;
color: #393E41;
}

article h2 {
text-transform: uppercase;
font-size: 3em;
}

#navbar {
position: fixed;
top: 0px;
left: 0px;
background-color: #393E41;
display: block;
width: 100%;
z-index: 100;
height: 60px;
}

#navbar nav {
display: flex;
}

#navbar nav a {
flex: 0 0 25vw;
text-align: center;
font-size: 2em;
background-color: #D3D0CB;
}

#navbar nav a:hover {


background-color: #393E41;
color: #E7BB41;
}

#wrapper {
margin-top: 60px;
}

#wrapper header {
min-height: 500px;
padding: 4px;
background-color: #E7BB41;
background: url(birds.png) no-repeat center center fixed;
background-size: cover;
}

#wrapper header > div {


border: 1px solid #393E41;
background-color: #E7E5DF;
border-radius: 15px;
width: 50%;
margin: auto;
text-align: center;
margin-top: 25px;
}

#wrapper header > div h2 {


font-size: 3em;
}

#wrapper > section {


min-height: 100vh;
padding: 30px;
background-size: cover;
background-position: center center;
}

#wrapper > section article {


background-color: rgb(231, 229, 223);
background-color: rgba(231, 229, 223, 0.8);
padding: 20px;
margin-top: 10px;
border-radius: 20px;
min-height: 500px;
}

#home {
background-image: url(img1.png);
}

#about {
background-image: url(img2.png);
}

#products {
background-image: url(img3.png);
}

#products ul {
margin: auto;
padding: 0;
list-style-type: none;
display: flex;
flex-wrap: wrap;
align-items: center;
text-align: center;
justify-content: center;
}
#products ul li {
margin: 10px;
text-align: center;
background-color: white;
}
#products ul li img {
box-shadow: 3px 3px 8px 0px rgba(0, 0, 0, 0.3);
max-width: 35vw;
border: 4px solid #000;
margin: 10px;
}
#contact {
background-image: url(birds.png);
}
#contact form {
margin: 0 auto;
max-width: 50vw;
border: 1px solid #ddd;
padding: 20px;
border-radius: 20px;
background-color: #44BBA4;
}
#contact label {
display: block;
width: 100%;
text-align: left;
margin-bottom: 20px;
font-size: 1.2em;
color: white;
}
#contact .row {
margin: 20px auto;
padding: 0 50px;
}
#contact input {
width: 100%;
font-size: 1.2em;
height: 55px;
border-radius: 10px;
padding-left: 10px;
}
#contact button {
padding: 15px;
width: 100%;
font-size: 1.4em;
background-color: #E7BB41;
}
#footer {
background-color: #393E41;
color: #E7E5DF;
padding: 20px;
text-align: center;
min-height: 200px;
}
@media all and (max-width:640px) {

#navbar nav a {
flex: 0 0 25vw;
font-size: 1.2em;
}
#navbar {
height: 30px;
}
#wrapper header > div {
width: 100%;
}
#wrapper header {
min-height: 100px;
}
#products ul li img {
box-shadow: 3px 3px 8px 0px rgba(0, 0, 0, 0.3);
max-width: 100%;
margin: 0px;
}
#contact form {
max-width: 100%;
}
}

OUTPUT:

You might also like