0% found this document useful (0 votes)
28 views

Web Development Long Term Notes

Uploaded by

manuboluakash346
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Web Development Long Term Notes

Uploaded by

manuboluakash346
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 114

WEB DEVELOPMENT LONG TERM COURSE

1.Origins and Evolution of the Internet :


The Internet originated from the Cold War era as a military-only
network. It was designed as a decentralized, indestructible
communication network to endure large-scale attacks. The Internet has
evolved from ARPANET, a research experiment initially meant to be a
communications system for
or computers)¹. Here's a detailed explanation:
1. History:
The WWW was initiated by CERN (European library for Nuclear
Research) in 1989¹. It was created by Timothy Berners-Lee for
researchers to work together effectively at CERN². The World Wide
Web Consortium (W3C) was developed for further development of the
web¹.

2. System Architecture:
From the user’s point of view, the web consists of a vast, worldwide
connection of documents or web pages. Each page may contain links to
other pages anywhere in the world¹. The pages can be retrieved and
viewed by using browsers¹.

3. Working of WWW:
The World Wide Web is based on several different technologies: Web
browsers, Hypertext Markup Language (HTML), and Hypertext Transfer
Protocol (HTTP)¹. A Web browser is used to access web pages¹.
Hyperlinked resources on the World Wide Web can be accessed using
software interfaces provided by Web browsers¹.

4. Features of WWW:

The WWW is a HyperText Information System that is cross-platform,


distributed, and uses open standards and open source¹. It uses web
browsers to provide a single interface for many services¹. It is dynamic,
interactive, and evolving¹.

5. Components of the Web:


There are 3 components of the web: Uniform Resource Locator (URL),
Hypertext Markup Language (HTML), and Hypertext Transfer Protocol
(HTTP)¹. A URL serves as a system for resources on the web¹.

6. Difference between World Wide Web and Internet:


Some people use the terms 'internet' and 'World Wide Web'
interchangeably. They think they are the same thing, but it is not so.
Internet is entirely different from WWW². The internet is a worldwide
network of devices like computers, laptops, tablets, etc³. It enables
users to send emails to other users and chat with them online². But,
when you have opened a website like google.com for information, you
are using the World Wide Web².
Webpage: A Web page is a document for the World Wide Web that is
identified by a unique uniform resource locator (URL). A Web page can
be accessed and displayed on a monitor or mobile device through a
Web browser
Website: A website is a collection of web pages and related content
that is identified by a common domain name and published on at least
one web server
types of website: 1.static website 2. Dynamic website
1. Static website: A website which has same content until the
developer of website makes any changes ex: college web portals
2. Dynamic website: A website which changes on regular time intervals
is called a dynamic website ex: weather app
3. Web application: A dynamic website where the data or
communication exchanged between the user and system. A web
application must be the dynamic

Webserver: which takes input request from the user and request client
for the response and displays the response in browser window

The Domain Name System (DNS) is the phonebook of the Internet.


Humans access information online through domain names, like
nytimes.com or espn.com. Web browsers interact through Internet
Protocol (IP) addresses. DNS translates domain names to IP addresses
so browsers can load Internet resources.
HTML
>"Hypertext" refers to links that connect web pages to one another,
either within a single website or between websites
>A markup language is a set of rules that defines how the layout and
presentation of text and images should appear in a digital document.
>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 is proposed by Tim berners lee the person who invented
internet
>in the period of 1993-1995
>HTML is orgined from SGML-standard generalized markup language
BASIC ELEMENTS OF HTML
Tag:tag is a unique keyword which is enclosed with angle bracket<>
Opening tag: <html>
Closing tag:</html>
HTML has two type of tags
1. paired tag: The tag which has both opening and closing tag
ex:<h1></h1>
2. unpaired tag: The tag which has only opening tag ex:<br>
Attributes:
Properties of an individual HTML tag
Ex: <h1 align=”centre”>hello world</h1>
Basic structure of HTML program
<!doctype HTML>
<html>
<head>
<title></title>
//supporting content of webpage like styles,scripts,libraries
</head>
<body>
//the main content of webpage
</body>
</html>
Heading tags:

>there are 6 types of tags


>they are h1,h2,h3,h4,h5

Paragraph

>html doesn’t allow the white spaces between the characters or words
so we need to use paragraph tag to display content in paragraph wise

>cheat code for space in HTML in &nbsp

List tag:

The <li> HTML element is used to represent an item in a list. we have 3


types of list tag

1.ordered list: To display list items in sequence order <ol></ol>

<ol type=”A” start=”7”><ol>

2.unordered list: to display list items in non

sequence order <ul></ul>

<ul type=”square”></ul>

3.description list: description list, description term, description data.

<dl>

<dt></dt>

<dd></dd>

</dl>

Different tags:<hr>,<br>
Text formatting in HTML:

>Change the colour of the text

Ex:<h1><font color=”red”>triaright</font></h1>

>for background color we need to apply it in body tag in html

Ex:<body bgcolor=”color”></body>

>face attribute is used to change the font style

Ex: <h1 face=”chiller” size=”10”>triaright</h1>

>to get bold text: <b></b>

>Italic text: <i></i>

>highlighter: <mark></mark>

>superscript: used to get power(square,cube) <sup></sup>

>subscript: <sub></sub>

>del: The <del> tag defines text that has been deleted from a
document.

>underline: to underline the text <u></u>

>marquee tag: The <marquee> tag is a container tag of HTML that is


implemented for creating scrollable text or images within a web page

Images and hyperlinks

The <img> tag is used to embed an image in an HTML page.

Attributes of img tag:


1.Src: source or url of image

2.alt: alternative text of img

3.height: to increase or decrease the height of image

4. width: to increase or decrease the width of image

5.title: used to show tool tip

online image :

<img src=”url of image”>

offline image:

<img src=imgname.jpg/png/jpeg/>

Browse the below extensions:

png, web p, jpg, jpeg, gif, psd

ANCHOR TAG

The <a> tag defines a hyperlink, which is used to link from one page to
another.

HYPERLINK:

>The href attribute specifies the URL of the page the link goes to.

>If the href attribute is not present, the <a> tag will not be a hyperlink.
Attributes:

Href>hyperlink reference

used to mention address of targeted web page

Target>where the target webpage should load either in same tab or in


new tab

_blank:open in new tab

_self:opens in same tab

<a href=”” target=_blank/_self;></a>

Tables in HTML

The <table> tag defines a

HTML table.An HTML table consists of one <table> element and one or
more <tr>, <th>, and <td> elements.

>The <tr> element defines a table row

> the <th> element defines a table header

> the <td> element defines a table data or cell.

Attributes:

1.border:used to add borders to table

2.cellpadding: the space between the cell context and its border.the
space inside the cell

3.cellspacing: the space between the cells of a table


4.Rowspan: merging of rows

5.Colspan: merging of columns

<table>

<tr>

<th>Month</th>

<th>Savings</th>

</tr

<tr>

<td>January</td>

<td>$100</td>

</tr>

</table>

Row span code:

<table>

<tr>

<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>
Colspan code:
<table>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>

Form in HTML:
The HTML <form> element is used to create an HTML form for user
input. The <form> element is a container for different types of input
elements, such as: text fields, checkboxes, radio buttons, submit
buttons, etc.
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 <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.
Type=text/number/date/email/password/checkbox/radio/submit/
reset/time/color/url
Code:
<form>
<label>name</label>
<input type="text" placeholder="" required pattern="[a-zA-Z]{3,10}">
<br>
<label><font color=”red”>*</font>phone number</label>
<input type="number" placeholder="" required pattern="[0-9]{10}">
<br>
<label>Gender</label>
<input type="radio" name="gen">Male
<input type="radio" name="gen">Female <br>
<label>linked in profile</label>
<input type="url" required placeholder=""> <br>
<label>date</label>
<input type="date" placeholder=""><br>
<label>time</label>
<input type="time" placeholder=""><br>
<label>fav color</label>
<input type="color" required placeholder="" > <br>
<input type="submit" value="register">
<input type="reset" value="reset">
</form>

Drop down: A dropdown menu is a toggleable menu that allows the


user to choose one value from a predefined list
Two types: 1.simple dropdown 2.data list
1.Simple dropdown:
<label>select passout year</label>
<select>
<option >2024</option>
<option >2023</option>
<option >2022</option>
<option >2021</option>
<option >2020</option>
<option >2019</option>
</select>
2.data list:
<label>select university</label>
<input list="name">
<datalist id="name">
<option>OU</option>
<option>JNTU</option>
<option>AU</option>
<option>KU</option>
<option>HCU</option>
</datalist>
22.`<button>`: The `<button>` tag defines a clickable button.

Multimedia
Onine video:
>select video click on share button
>select embded
>copy the iframe tag place in code

Offline video:
The <video> tag is used to embed video content in a document, such as
a movie clip or other video streams.
Code:
<video controls height=”” width=”” autoplay muted loop> //use auto
play and muted attribute to autoplay the video
<source src=”filename.mp4”>
</video>

Audio:
<audio controls>
<source src=””filename.mp3>
</audio>

Iframe tag:
The <iframe> tag specifies an inline frame.
An inline frame is used to embed another document within the current
HTML document.

Block level elements


>it will start from new line
>it will occupy the available screen width
>it will have default padding
Examples:<header>,<fieldset>,<footer>, <p>etc

Inline level elements


>it will start from existing line
>it will occupy only required screen width
>it doesn’t have padding
Examples:<input>,<button> etc

HTML Semantic Elements


A semantic element clearly describes its meaning to both the browser
and the developer.
Examples of non-semantic elements: <div> and <span> - Tells nothing
about its content.
Examples of semantic elements: <form>, <table>, and <article> - Clearly
defines its content.
semantic HTML can improve document structure:
CSS(cascading style sheet)
CSS is used to define styles for your web pages, including the design,
layout, and variations in display for different devices and screen sizes.
CSS saves a lot of work as it can control the layout of multiple web
pages all at once. External stylesheets are stored in CSS files
different types of CSS:
1.Inlinecss : used to apply style for only single element
ex: <h1 style="color:red">triaright</h1>
2.Internal: used to apply styles for entire webpage. we need to use
style tag to apply styles to elements
<style>
h1{
backgroundcolor:"yellow";
}
</style>
3.External: used to apply styles to entire website. we need to write
styles in seperate file and save that file using .css extension
<link rel="stylesheet" href="filename.css">
insert this link tag inside the head tag
CSS Selectors
It is a keyword which is used to apply one block of css to all
html elements.we have 4 types of selectors
1.Tag name selector: we can apply a block of css to html elements by
using its tag name
p{
color:"red";
}
2.Class name selector: The .class selector selects elements with a
specific class attribute. we need to use dot(.) as delemeter to apply CSS
to class name
<h1 class="myh1">Triaright</h1>
<style>
.myh1{
background-color:"powderblue";
}
</style>
note:class name can be duplicate
3.id name selector:
The #id selector styles the element with the specified id.. we need to
use hash(#) as delemeter to apply css to id name
<h1 id="myh1">Triaright</h1>
<style>
#myh1{
background-color:"powderblue";
}
</style>
note:id name must be unique
4.universe selector: It is used to apply a block of css to all HTML
elements. applies color for every element in the body where as in body
applies only once we need to use * as delemeter
4 types of colour formats:
1.color name: ex color:red;
2.hexa value: A hexadecimal colour is specified with: #RRGGBB,
where the RR (red), GG (green) and BB (blue) hexadecimal integers
specify the components of the colour. 0-9 and a-f. here 0 is small and f
is high. If we take ff0000 it displays red colour because red is set to be
in high.
Ex: color:#rrggbb color:ff0000

3.rgb value: rgb(0


-255,0-255,0-255)
In HTML, a color can be specified as an RGB value, using this formula:
rgb(red, green, blue). Each parameter (red, green, and blue) defines the
intensity of the color with a value between 0 and 255.
4.hsl values: hsl(0-360, upto100%, upto100%)
HSL stands for hue, saturation, and lightness.
Hue is a degree on the colour wheel from 0 to 360. 0 is red, 120 is
green, and 240 is blue.
Saturation is a percentage value. 0% means a shade of gray, and 100%
is the full color.
Lightness is also a percentage value. 0% is black, and 100% is white.

CSS Backgrouds
1.background image: used if we want multiple color in background.
To apply multiple colors in background we need to use linear gradient
Ex code:
body{
background-image: linear-gradient(to left, red, yellow,green);
}
radial-gradient:
h1{
background-image: radial-gradient( red, yellow,green);
}
2.background-image:url(‘url/filename’);
To change background image of webpage.if the size of the image is less
it will repeat image.
body{
background-image: url('cricket.jpg');
}
3.background-repeat:
background-repeat: no-repeat/repeat-x/repeat-y/;
4.background-position:to cha
nge the position of background
background-repeat: no-repeat;
Background-position:center/top right/top left/bottom left/bottom
right;
5.background-size:to change size of background
Background-size:cover/px values
6.background-attachement:to fix or scroll the background
Background-attachment:fixed/scroll;

Text formatting:
1.to change the color of text: color
:value
2.to change the face(style) of the text font-family:value;
3.to change the size of text font-size:value;
4.to change weight of text font-weight:value;
5.to change the style of text font-style:value;

6.to change the height between the lines of paragraph


line-height:value
7.to change the space between the words of content
Word-spacing:value;
8.to change the space between the letters of words
Letter-spacing:value;
9.to change the case of text
Text-transform:value;
10.to add lines for the text
Text-decoration:none/solid/dotted/dashed/double;
Text-decoration-style:value;
11.to add shadow to the text
Text-shadow:height px width px color;
12.to change alignment of text
Text-align:value;
13.to add indentation to paragraph
Text-indent:value
psuedo classes:used to define the styles for different styles for different
states of HTML element(:)
Attributes:
1.link:unvisited state of an anchor tag
2.hover:whenever user hovered with mouse on an element
3.visited:we already visited the targeted webpage
4.active:whenever user clicked on anchor tag

a:link{
color:blue;
}
a:hover{
color:brown;
}
a:visited{
color:chartreuse;
}
a:active{
color:deeppink;
}

positions:the position property specifies the type of positioning


method used for element

position:absolute=>changes applied from its ancestor element


position:relative=>changes applied from normal position
position:static=>we can’t apply the changes in alignment
position:fixed=>it doesn't change the position
.img1{
position:absolute;
left:200px;
}
.img2{
position:relative;
left:200px;
}
.img3{
position:static;
left:150px;
}
<div class="img1"><img src="cricket.jpg"></div><br><br>
<div class="img2"><img src="cricket.jpg"></div>
<div class="img3"><img src="cricket.jpg"></div>
position:fixed:
nav{

position:fixed;
top:0px;
}

BOX MODEL:
The box model allows us to add a border around elements, and to
define space between elements. The total width and height of an
element should be calculated like this:

Margin:the space between sides of webpage and content


Padding:the space between content and border
Border:the line around the content
Outline:the external line around the border and content
Outline-offset:the space between border and outline

Margin-left:px
Margin-top:px;
Border:width style color;
Padding:px;
To get curved edges for borders
Border-radius:50px;
To apply border and css for tables
Table,tr,td,th{
Padding:20px;
Border:2px solid black;
Border-collapse:collapse //to remove excessive borders
}
Psuedo classes:used to define the styles for different states of HTML
elements.
Attributes
1.link:unvisited state of an anchor tag
2.hover:whenever user hovered with mouse
3.visited:we already visited the targeted web page
4.active:whenever user clicked on anchor tag
nth child:
The :nth-child(n) selector matches every element that is the nth child of
its parent. n can be a number, a keyword (odd or even), or a formula
(like an + b).
<style>
Table,td,th{
Border:2px,solid grey;
Padding:2px;
Border-collapse:collapse;
}
Tr.nth-child(even(or)odd){
Background-color:pink;
}
</style>
<body><table></table></body>
Pseudo properties:used to define styles for special parts of an element
Use(::) to implement pseudo properties.
1.first-letter
2.first-line
3.before-to apply content before code for “n” no.of tags
4.after:
5.selection:
<style>
P::first-letter{
Color:blue;
Text-transform:uppercase;
Font-family:chiller;
}
P::first-line{
Color:blue;
Text-transform:uppercase;
Font-family:chiller;
}
H1::before{
Content:’*’;
}
H1::after{
Content:’*’;
}
P::selection{
Background-color:red;
Color:black;
}
</style>
Display:we can define an HTML element how it can be
displayed on the screen.there are 3 different ways to use this display
properties

Display:inline/block/none(none is used to hide content)


Drop down.
OVER FLOW
Overflow:over flow is used to adjust the excessive content.
Overflow:auto/scroll/hidden/none
Transformation: used to change HTML element into different style like
translate,rotate,scale,skew
Translate:used to change alignment of an element with respective to
coordinates(x-axis,y-axis)
H1{
Transform:translate(550px,1200);
}
Rotate: used to rotate an element
H1{
Transform:rotate(50deg);
}
Skew:process of converting a rectangle into parallelogram
H1{
Transform:skew(10 deg);
}
Scale:to increase the height and width of an element
H1{
Transform:scale(2,3)
}
Transitions:used to apply smooth changes to an element
Div{
Transition:width 3s,height 2s,transforms 3s;
Transition-delay:2s;
}
Div:hover{
Height:40px;
Width:400px:
Transition:rotate(180deg);
}

Flexbox
Flex box is used to design responsive layout without using positons and
float elements We need a flex container to design the layout We can
create flex container by using display:flex; property
1.Flex-direction:
to set directions for child elements in flexbox
Flex-direction:row/row-reverse/column/column-reverse
2.Justify-content=&gt;to set alignment
Justify-content:start/center/end/space-between/space-around
3. flext-wrap=&gt;to arrange all the elements with in the specified
size
Flex-wrap:wrap/no-wrap
JAVA SCRIPT

>java script is cross platformed and object oriented, scripting language.


>Monolithic-we write entire code in a single file
>java script was invented by brendan eich 1955
1955>brendan eich>net scape
>java script follows Ecmpa script
>Ecmascript is a specification to create one scripting language
>Ecmascript is a specification, JS is the language to implement that
specification.
>version of js-ES6.

Features of java script:


>arrow functions
>Date object
>Map
>for each
>functional constructor

Difference between java and java script


1.java is a class based implementation language while JS works
prototype based
2.java is static type while JS is dynamically typed
3.java is programming language JS is language
4.java byte code implementation JS does not have intermediate code
5.java is used on server side but JS used for client side and server side

Java script uses


1.data validation
2.Dynamic features in web page
3.to fetch REST API
4.DOM manipulation
5.HTML Manipulation
6.CSS manipulation
7.server implementation

Types of java script:


there 2 types of script to include in HTML page
1.internal JS
>we can include internal js in body tag as well
2.external js
>creates new .js file and include it in head or body by using
<script src="filename.js"></script>
Output statements
4 types of output statements
1.document.write()
Write:is the method to print content in active webpage
2.innerHTML:
Document:active webpage in the browser
To print content on webpage along with existed html elements
3.console.log:
To display output in console page
4:alert:
Print one dialogue box on web page

Variables
● Variables are Containers used for Storing Data.
● In JavaScript, a variable is like a container / box where you can store
different types of data, such as numbers, text, or even functions. You
can then use the name of the box (the variable) to access or change the
data stored inside.
Two types of variables: 1.local variable 2.global variable
1.local variable: A variable which is declared with in the block(a
function, a method, a class) is called local variable. We can use key
word called ‘let’.
2.global variable:A variable which is declared outside of the block. We
can use a key word called ‘var’.
3.const: This is used to declare variables that should not change once
they're assigned a value.

Variable Naming Conventions : [Rules]


● Names can contain letters, digits(0-9), underscores_, and $dollar
signs.
● Names must begin with a letter[A-Z]/[a-z].
● Names can also begin with $ and _
● Names are case sensitive (age and Age are different variables).
● Reserved words (like JavaScript keywords) cannot be used as variable
names

Data types
It specifies the type of data that we are working in variables. Java script
supports all types of data like number, float, Boolean, char, string, date,
object.
1.String: A string is a series of characters, like a word or a sentence. You
can use single or double quotes to create a string.
For example:
Let name=”triaright”;
2.number: The number data type can hold both integer and floating-
point numbers. There's a small difference between integers and
floating-point numbers in JavaScript.
For example:
Let x=10;
3.bigInt: BigInt is a special numeric type that can work with arbitrarily
large integers.
For example:
var x=BigInt(8**55)
document.write(x);
4.Boolean: Boolean represents a logical entity and can have two values:
true or false. It's often used in conditional statements.
For example:
<script>
let x = 5;
let y = 5;
let z = 6;
document.getElementById("demo").innerHTML =
(x == y) + "<br>" + (x == z);
</script>
5.undefined: A variable that has not been assigned a value is
undefined.
For example
let testVar;
console.log(testVar);
6.null: This is a special value that represents "nothing", "empty" or
"value unknown".
For example
Let val=””;
7.object: Objects are used to store keyed collections of various data
and more complex entities¹. Objects in
JavaScript can be thought of as a collection of properties¹. For example:
```javascript
let student = {
Id:123,
firstName: 'John',
lastName: 'Doe',
age: 20
};

Operators
JavaScript operators are symbols that perform operations on variables
and values. They allow you to manipulate and perform calculations on
data. Here's an overview of some common JavaScript operators:
Arithmetic Operators: Arithmetic operators in JavaScript are symbols or
keywords that perform mathematical operations on variables or values.
These operations include addition, subtraction, multiplication, division,
and modulus.
● Addition +
● Subtraction -
● Multiplication *(asterisk)
● Division /
● Modulus % (returns the remainder of a division)
● Increment ++
● Decrement –¬
Code:
let a = 10;
let b = 3;
let sum = a + b; // 13
let difference = a - b; // 7
let product = a * b; // 30
let quotient = a / b; // 3.333...
let remainder = a % b; // 1
let x = 5;
x++;
document.write(x + "<br>")
let y=6;
y--;
document.write(y);
Assignment Operators:
Assignment operators in Java Script, are symbols used to assign values
to variables. They combine the act of assigning a value to a variable
with an arithmetic operation.
● Assignment =
● Add and assign +=
● Subtract and assign -=
● Multiply and assign *=
● Divide and assign /=
● Modulus and assign %=
● Exponent and assign **=
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y

Example code for +=:


let x = 10;
x+=5;
document.getElementById("demo").innerHTML="x is" + x;
Comparison operators
Comparison operators in JavaScript are used to compare values and
return a Boolean result indicating the relationship between the values.
These operators are commonly used in conditional statements and
expressions to make decisions based on whether a certain condition is
true or false.
● Equal to == (compares value)
• === (compares value and datatype)
● Not equal to != (not equal value)
• !== (not equal value and type)
● Greater than >
● Less than <
● Greater than or equal to >=
● Less than or equal to <=
Code:
let a = 5;
let b = 10;
console.log(a == b);
console.log(a === b);
console.log(a != b);
console.log(a !== b);
console.log(a > b);
console.log(a < b);

Logical Operators:
Logical operators in JavaScript are used to perform logical operations
on Boolean values. These operators allow you to combine or
manipulate Boolean values to make more complex decisions in your
code.
● AND &&
● OR ||
● NOT !
Code:
let x = true;
let y = false;
console.log(x && y); // false (AND)
console.log(x || y); // true (OR)
console.log(!x); // false (NOT)

Conditional Statements
If Statement:
The if statement is used to specify a block of code to be executed if a
specified condition is true
Syntax :
if (condition) {
// block of code to be executed if the condition is true
}
Code:
let num = 20;
if (num % 2 === 0) {
console.log("Given number is even number.");
}
If-Else Statement:
The if-else statement is used to specify a block of code to be executed if
a condition is true, and
another block of code to be executed if the same condition is false.
Syntax:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Code:
let age = 25;
if (age >= 18) {
console.log("You are eligible for driving licence");
} else {
console.log("You are not eligible for driving licence");
}
Else If Statement:
The else if statement is used to specify a new condition to test if the
first condition is false.
Syntax:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2
is true
} else {
// block of code to be executed if the condition1 is false and condition2
is false
}
Code:
let temperature = 28;
if (temperature > 30) {
console.log("It's hot outside");
} else if (temperature > 20) {
console.log("It's warm outside");
} else {
console.log("It's cool outside");
}
Switch Statement:
The switch statement is used to select one of many blocks of code to be
executed. It’s often used when you want to select one of many code
blocks to be executed.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
} code:
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
Javascript Loops

For Loop:
A for loop is a control structure used to repeat a block of code a fixed
number of times1. It’s defined with three expressions: initialization,
condition, and increment.
JavaScript
for (let i = 0; i < 5; i++) {
console.log(i); // This will print numbers 0 through 4
}
In the example above, i is initialized to 0, the loop continues as long as i
is less than 5, and i is incremented by 1 after each loop iteration.
While Loop:
A while loop is a control structure that executes a block of code as long
as a specified condition is true.

JavaScript
let i = 0;
while (i < 5) {
console.log(i); // This will print numbers 0 through 4
i++;
}
In the example above, the loop will continue to run as long as i is less
than 5
i is incremented by 1 after each loop iteration.
1.Java script program reverse of a number using while loop
var num=400, rem, rev=0
while(num!=0){
rem=num%10;
rev=rev*10+rem;
num=parseInt(num/10);
}
document.write("reverse of 123 is" + rev);
2.Java script program to check weather palindrome or not
function isPalindrome(str) {
let rev = "";
for (let i = str.length - 1; i >= 0; i--) {
rev += str[i];
}
if (rev == str) {
return true
} else {
return false;
}
}

let str1 = "racecar";


let str2 = "nitin";
let str3 = "Rama";

console.log(isPalindrome(str1));
console.log(isPalindrome(str2));
console.log(isPalindrome(str3));
3.Java script program to print reverse of string.
// Function to reverse string
function reverseString(str) {
let strRev = "";
for (let i = str.length - 1; i >= 0; i--) {
strRev += str[i];
}
console.log(strRev);
}

// Function call
reverseString("JavaScript");
reverseString("TypeScript");

Do-While Loop:
A do-while loop is similar to a while loop, but the block of code is
executed at least once before the condition is checked.
JavaScript
let i = 0;
do {
console.log(i); // This will print numbers 0 through 4
i++;
} while (i < 5);
In the example above, the loop will first print 0, and then it will check if
i is less than 5.
For-In Loop:
The for-in loop is used to loop through the properties of an object1.
JavaScript
Let person = {firstName:"John", lastName:"Doe", age:25};
for (let key in person) {
console.log(key + ": " + person[key]);
}
In the example above, the loop will log each property and its value of
the person object
For-Of Loop:
The for-of loop is used to loop through the values of an iterable object,
like an array.
JavaScript
let colors = ['red', 'green', 'blue'];
for (let color of colors) {
console.log(color);
}
In the example above, the loop will log each color in the colors array.
Remember, loops are a powerful feature that let you repeat a block of
code until a certain condition is met. They’re extremely useful for tasks
that require the same code to be executed multiple times.

Java script arrays


What are Arrays in JavaScript?
An array in JavaScript is a special variable, which can hold more than
one value at a time1. If you have a list of items (a list of car names, for
example), storing the cars in single variables could look like this: let car1
= "Saab"; let car2 = "Volvo"; let car3 = "BMW"; However, what if you
want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300? The solution is an array1!
Here’s an example of creating an array:
JavaScript
const cars = ["Saab", "Volvo", "BMW"];
In this example, cars is an array that holds three elements1.
Accessing Array Elements :
You access an array element by referring to the index number. Note:
Array indexes start with 0. [0] is the first element. 1 is the second
element1.
Here’s an example of accessing array elements:
JavaScript
const cars = ["Saab", "Volvo", "BMW"];
let car = cars[0];
console.log(car); // Outputs: Saab
In this example, we’re accessing the first element of the cars
array1.Changing an Array Element : This statement changes the value
of the first element in cars1:
JavaScript
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
console.log(cars[0]); // Outputs: Opel
In this example, we’re changing the first element of the cars array1.
Converting an Array to a String:
The JavaScript method toString() converts an array to a string of
(comma separated) array values1.
Here’s an example:
JavaScript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.toString()); // Outputs: Banana,Orange,Apple,Mango
In this example, we’re converting the fruits array to a string1.
Access the Full Array With JavaScript:
the full array can be accessed by referring to the array name1.
Here’s an example:
JavaScript
const cars = ["Saab", "Volvo", "BMW"];
console.log(cars); // Outputs: [ 'Saab', 'Volvo', 'BMW' ]
In this example, we’re accessing the full cars array.
Remember, arrays in JavaScript are a fundamental part of the language
and are used to group related data and functions together1. They
provide a way to structure your code in a modular and reusable way1
Array methods
push() Method :
The push() method adds new items to the end of an array, and returns
the new length1.
Here’s an example:
JavaScript
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Mango");
console.log(fruits); // Outputs: [ 'Banana', 'Orange', 'Apple', 'Mango' ]
In this example, we’re adding “Mango” to the end of the fruits array1.
pop() Method:
The pop() method removes the last element from an array, and returns
that element1.
Here’s an example:
JavaScript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let poppedFruit = fruits.pop();
console.log(poppedFruit); // Outputs: Mango
console.log(fruits); // Outputs: [ 'Banana', 'Orange', 'Apple' ]
In this example, we’re removing the last element from the fruits array1.
shift() Method:
The shift() method removes the first array element and “shifts” all
other elements to a lower index1.
Here’s an example:
JavaScript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let shiftedFruit = fruits.shift();
console.log(shiftedFruit); // Outputs: Banana
console.log(fruits); // Outputs: [ 'Orange', 'Apple', 'Mango'
In this example, we’re removing the first element from the fruits
array1.
unshift() Method:
The unshift() method adds new items to the beginning of an array, and
returns the new length1.
Here’s an example:
JavaScript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
console.log(fruits); // Outputs: [ 'Lemon', 'Banana', 'Orange', 'Apple',
'Mango' ]
In this example, we’re adding “Lemon” to the beginning of the fruits
array1.
const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
// At position 2, remove 2 items:
fruits.splice(2, 2);
console.log(fruits);
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
console.log(fruits);
toString() Method:
The toString() method converts an array to a string of (comma
separated) array values1.
Here’s an example:
JavaScript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.toString()); // Outputs: Banana,Orange,Apple,Mango
In this example, we’re converting the fruits array to a string1.
join() Method:
The join() method also joins all array elements into a string. It behaves
just like toString(), but in addition you can specify the separator1.
Here’s an example:
JavaScript
const fruits = ["Banana", "Orange", "Apple", "Mango"];
console.log(fruits.join(" * ")); // Outputs: Banana * Orange * Apple *
Mango
In this example, we’re joining the fruits array into a string with " * " as
the separator1.
Remember, array methods in JavaScript are a fundamental part of the
language and are used to manipulate arrays1. They provide a way to
structure your code in a modular and reusable way.
delete() method:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
slice() method:
The slice() method creates a new array.The slice() method does not
remove any elements from the source array.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1,3);
splice() method:
The first parameter (2) defines the position where new elements should
be added (spliced in).
The second parameter (0) defines how many elements should be
removed
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");

Java script strings

What are Strings in JavaScript?


Strings in JavaScript are used for storing and manipulating text1. A
JavaScript string is zero or more characters written inside quotes1. You
can use single or double quotes1.
Here’s an example of creating a string:
JavaScript
let text = "John Doe";
In this example, text is a string that holds the value "John Doe"1.
Quotes Inside a String:
You can use quotes inside a string, as long as they don’t match the
quotes surrounding the string1.
Here’s an example:
JavaScript
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';
In these examples, we’re using different types of quotes inside and
outside the strings1.
String Length:
To find the length of a string, use the built-in length property1.
Here’s an example:
JavaScript
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
console.log(length); // Outputs: 26
In this example, we’re finding the length of the string text1.
Escape Character The backslash (\):
Enhgscape character turns special characters into string characters1.
The sequence \" inserts a double quote in a string, the sequence \’
inserts a single quote in a string, and the sequence \\ inserts a
backslash in a string1.
Here’s an example:
JavaScript
let text1 = "We are the so-called \\\"Vikings\\\" from the north.";
let text2 = 'It\\'s alright.';
let text3 = "The character \\\\ is called backslash.";
In these examples, we’re using the backslash to escape special
characters1.
Breaking Long Code Lines:
For best readability, programmers often like to avoid code lines longer
than 80 characters. If a JavaScript statement does not fit on one line,
the best place to break it is after an operator1.
Here’s an example:
JavaScript
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
In this example, we’re breaking a long string into two lines1.
Remember, strings in JavaScript are a fundamental part of the language
and are used to store and manipulate text1. They provide a way to
structure your code in a modular and reusable way1.

Javascript string methods


length Property The length property returns the length of a string1.
Here’s an example:
JavaScript
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
console.log(length); // Outputs: 26
In this example, we’re finding the length of the string text1.
slice() Method:
The slice() method extracts a part of a string and returns the extracted
part in a new string1.
Here’s an example:
JavaScript
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);
console.log(part); // Outputs: Banana
In this example, we’re slicing out a portion of a string from position 7 to
position 131.
substring() Method:
The substring() method is similar to slice(). The difference is that start
and end values less than 0 are treated as 0 in substring()1.
Here’s an example:
JavaScript
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
console.log(part); // Outputs: Banana
In this example, we’re extracting a substring from a string1.
substr() Method:
The substr() method is similar to slice(). The difference is that the
second parameter specifies the length of the extracted part1.
Here’s an example:
JavaScript
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
console.log(part); // Outputs: Banana
In this example, we’re extracting a part of a string1.
Replace() Method: The replace() method replaces a specified value
with another value in a string1.
Here’s an example:
JavaScript
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
console.log(newText); // Outputs: Please visit W3Schools!
In this example, we’re replacing “Microsoft” with “W3Schools” in the
string1.
toUpperCase() and toLowerCase() Methods The toUpperCase()
method converts a string to uppercase letters, and the toLowerCase()
method converts a string to lowercase letters1.
Here’s an example:
JavaScript
let text = "Hello World!";
console.log(text.toUpperCase()); // Outputs: HELLO WORLD!
console.log(text.toLowerCase()); // Outputs: hello world!
In this example, we’re converting a string to uppercase and lowercase1.
concat() Method:
The concat() method joins two or more strings1.
Here’s an example:
JavaScript
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
console.log(text3); // Outputs: Hello World
In this example, we’re concatenating two strings1.
trim() Method:
The trim() method removes whitespace from both ends of a string1.
Here’s an example:
JavaScript
let text = " Hello World! ";
console.log(text.trim()); // Outputs: Hello World!
In this example, we’re trimming whitespace from a string1.
Remember, string methods in JavaScript are a fundamental part of the
language and are used to manipulate strings1. They provide a way to
structure your code in a modular and reusable way1.

Javascript Functions
What are Functions?
A function in JavaScript is a block of reusable code designed to perform
a specific task1. You can think of a function as a sub-program within the
main program2. A function consists of a set of statements but executes
as a single unit2.
1.simple function
1.Function sample(){
Document.write(“hello world”);
}
Sample()

2.Function with parameter and return type


function addoftwo(a,b)
{
return a+b;
document.write("addition of two");
}
let res=addoftwo(5,7)
document.write(res);

3.Arrow Functions:
Arrow functions provide a concise syntax to write functions in
JavaScript. They are especially useful when you want to write an
anonymous function in a single line, or if you are writing a lot of nested
functions. Here’s an example:
JavaScript
const add = (a, b) => a + b;
console.log(add(5, 3)); // Outputs: 8
4.Anonymous Functions:
Anonymous functions are functions that are declared without any
named identifier to refer to it. As such, an anonymous function is
usually not accessible after its initial creation. Here’s an example:
JavaScript
let x = function (a, b) {
return a * b;
};
console.log(x(4, 3)); // Outputs: 12
5.For each:for each is used to apply function for every element of an
array by iterating them.

var arr=[10,11,12,13,14,15];
arr.forEach((i)=>{if(i%2==0){document.write(i+"<br>")}});

6.map:map is used to call a function for every element of an array and


it returns new array.
var arr=[1,2,3,4,5,6];
var newarr=arr.map((item)=>{return item*5})
document.write(newarr);

7.filter:filter m
ethod is used to create new array from the given array consisting of
those elements which satisfied with a condition
var arr=[1,2,3,4,5,6];
var newarr=arr.filter((item)=>{return item%2==0})
document.write(newarr);

8.reduce:reduce methods used to reduce the array of elements into


single value
let sum=(i,j)=>{return i+j}
var arr=[1,2,3,4,5]
var sumofnum=arr.reduce(sum,6);
document.write(sumofnum);
9.Async Functions:
Async functions are used to write promise-based asynchronous code as
if it were synchronous, but without blocking the execution thread. They
are defined with the async keyword.
What are Methods in JavaScript?
A method in JavaScript is a property of an object that contains a
function definition3. Methods are functions stored as object
properties4.
Here’s an example of a method:
JavaScript
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // Outputs: John Doe

DOM Selection and Manipulation


The DOM (Document Object Model) is a tree-like structure that
represents the structure of a web page1. It consists of a collection of
nodes, each of which represents an element of the page, such as a
heading, a paragraph, or a button. Each of these nodes has its own
properties and methods which can be manipulated using JavaScript.

DOM Selection:
To manipulate the DOM, you first need to select the element you
want to work with. Here are some common ways to select elements:
1.getElementById:
This method gets the element with the specified ID.
example 1:
<body>
<p id="mypara">new era of learning</p>
<p id="demo"></p>
<script>
const element=document.getElementById("mypara");
document.getElementById("demo").innerHTML="the text from first
para is:: " + element.innerHTML;
</script>
</body>
example 2
<body>
<h1 id="demo">DOM Manipulations</h1>
<button onclick="changecolor()">click me</button>
<script>
function changecolor(){
var res=document.getElementById("demo").style.color="red";;
}
</script>
</body>
2.getElementsByClassName: This method gets all elements with the
specified class name1.
example 1:
<body>
<p>Triaright</p>
<p class="demo">finding elements by tag name</p>
<p class="demo">dom manipulations</p>
<p id="myid"></p>
<script>
const element=document.getElementsByClassName("demo");
document.getElementById("myid").innerHTML="the text in first
para: " + element[1].innerHTML;
</script>
</body>
example 2:
<body>
<h2 class="demo">hello world</h2>
<p class="demo">Triaright new era of learning</p>
<h1 >DOM Manipulations</h1>
<button onclick="changecolor()">click me</button>
<script>
function changecolor(){
var res=document.getElementsByClassName("demo");
res[0].style.color="pink";
res[1].style.color="yellow";
}
</script>
</body>
3.getElementsByTagName:
This method gets all elements with the specified tag name1.
example 1:
<body>
<p>finding elements by tag name</p>
<p>dom manipulations</p>
<p id="demo"></p>
<script>
const element=document.getElementsByTagName("p");
document.getElementById("demo").innerHTML="the text in first
para: " + element[0].innerHTML;
</script>
</body>
example 2:
<body>
<h1>hello world</h1>
<h1>DOM Manipulations</h1>
<button onclick="changecolor()">click me</button>
<script>
function changecolor(){
var res=document.getElementsByTagName("h1");
res[0].style.color="red";
res[1].style.color="blue";
}
</script>
4.querySelectorAll:
This method gets all elements that match a specified CSS selector1.
<body>
<p>Triaright</p>
<p class="demo">finding elements by tag name</p>
<p class="demo">dom manipulations</p>
<p id="myid"></p>
<script>
const element=document.querySelectorAll("p.demo");
document.getElementById("myid").innerHTML="the text in first
para: " + element[0].innerHTML;
</script>
</body>

DOM Manipulation:
Once you’ve selected an element, you can manipulate it in various
ways. Here are some common manipulations:

Changing Content:
You can change the content of an element using the textContent or
innerHTML property1.
JavaScript
let titleElement = document.getElementById('title');
titleElement.textContent = 'New Title'; // Changes the text content of
the element with id 'title'
code:
<p id="demo" onclick="myFunction()">Click me to change my textual
content.</p>
<script>
function myFunction() {
document.getElementById("demo").textContent = "I have changed!";
}
</script>
Changing Attributes:
You can change the attributes of an element using the setAttribute
method1.
JavaScript
let titleElement = document.getElementById('title');
titleElement.setAttribute('class', 'highlight'); // Changes the class of the
element with id 'title' to 'highlight'
code:
<style>
.democlass {
color: red;
}
</style>
<body>
<h1 id="myH1">The Element Object</h1>
<p>Click "Add Class" to add a class attribute to the h1 element:</p>
<button onclick="myFunction()">Add Class</button>
<script>
function myFunction() {
document.getElementById("myH1").setAttribute("class",
"democlass");
}
</script>
Changing Styles: You can change the CSS styles of an element using the
style property.
JavaScript
let titleElement = document.getElementById('title');
titleElement.style.color = 'blue'; // Changes the color of the text in the
element with id 'title' to blue
Code:
<h1 id="ramya">event handling</h1>
<button onclick="change()">click</button>
<script>
function change()
{
document.getElementById("ramya").style.color="red"; onclick
code
}
</script>

Adding and Removing Elements:


You can add new elements using the createElement and appendChild
methods, and remove elements using the removeChild method1.
JavaScript
let newParagraph = document.createElement('p');
newParagraph.textContent = 'New Paragraph';
document.body.appendChild(newParagraph); // Adds a new paragraph
to the end of the body
let titleElement = document.getElementById('title');
document.body.removeChild(titleElement); // Removes the element
with id 'title' from the body

Events in java script


What is an Event?
An event in JavaScript represents the state change of an object. This
could be due to user actions (like clicking a button) or browser actions
(like loading a web page).
What is Event Handling?
Event Handling is the process of setting up certain functionality to occur
when an event is fired.For example, you might want to display a
message when a button is clicked.
User events:
1.onclick
2.onchange
3.onmouseout
4.onmouserover
5.onmouseup
6.onmousedown
System events
7.onload
8.ononline
9.onoffline
10.onresize
1.Onclick: Used to call a function when user clicks on a button
Code:
<h1 id="ramya">event handling</h1>
<button onclick="change()">click</button>
<script>
function change()
{
document.getElementById("ramya").style.color="red"; onclick
code
}
</script>
2.onchange: used to call a function whenever the value changed in the
input box
Code:
<body>
<label>YOB</label>
<br>
<input type="text" id="yob" onchange="agecal()">
<label id="age"></label>
<script>
function agecal(){
var year=document.getElementById("yob").value;
var age=2024-year;
document.getElementById("age").innerHTML="age is"+age;
}
</script>
</body>
3.onmouseout
4.onmouseover
Used to call a function whenever user hovered the content with mouse
Code:
<body>
<h1>HTML DOM Events</h1>
<h2>The onmouseover Event</h2>
<img onmouseover="overimg(this)" onmouseout="leaveimg(this)"
src="image.jpg" width="32" height="32">
<script>
function overimg(bs) {
bs.style.height = "64px";
bs.style.width = "64px";
}

function leaveimg(bs) {
bs.style.height = "32px";
bs.style.width = "32px";
}
</script>
</body>

5.onmouseup
6.onmousedown
Used to call a function whenever mouse right click is pressed and
coming back to its original position is called onmouseup and down
Code:
<body>
<h1>mouse up down events</h1>
<p id="myphara" onmousedown="mousedown()"
onmouseup="mouseup()">Lorem ipsum</p>
<script>
function mousedown(){
document.getElementById("myphara").style.color="red";
}
function mouseup(){
document.getElementById("myphara").style.color="blue";
}
</script>
</body>

7.onload: The onload event occurs when an object has been loaded.
Code:
<body onload="myFunction()">
<h1>HTML DOM Events</h1>
<h2>The onload Event</h2>
<script>
function myFunction() {
alert("Page is loaded");
}
</script>
</body>
8.ononline: Call a function when the browser starts to work online
9.onoffline: Call a function when the browser starts to work offline
Used to call a function when the new connection is lost and when
connection is back we use on online
Code:
<body ononline="onFunction()" onoffline="offFunction()">
<h1 id="myh1"></h1>
<script>
function onFunction() {
document.getElementById("myh1").innerHTML = "login";
document.getElementById("myh1").style.color="green"
}
function offFunction() {
document.getElementById("myh1").innerHTML = "connection lost";
document.getElementById("myh1").style.color="red";
}
</script>
</body>

10.onresize: Call a function when the browser window is resized


<html>
<body onresize="myFunction()">
<p>Try to resize the browser window to display the windows height
and width</p>
<p id="demo"></p>
<script>
function myFunction() {
let w = window.outerWidth;
let h = window.outerHeight;
let txt = "Window size: width=" + w + ", height=" + h;
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>

Event listener:An event listener is a function in JavaScript that waits for


an event to occur then responds to it
1.addEventListener():The addEventListener() method attaches an event
handler to an element.
2.removeEventListener():The removeEventListener() method removes
an event handler from an element.
note:the call back reference should be same to remove
code:
<button id="dom">click me<button>
<script>
const element=document.getElementById("dom");
element.addEventListener('click',(evt)=>{
console.log("button 1 was clicked");
})
element.addEventListener('click',(evt)=>{
console.log("button 2 was clicked");
})
const x=()=>{
console.log("button 3 was clicked");
};
element.addEventListener("click",x);

element.addEventListener('click',(evt)=>{
console.log("button 4 was clicked");
})
element.removeEventListener("click",x);

</script>

Creating and Appending elements

1. Creating an Element
In JavaScript, you can create a new element using the
document.createElement() method.
This method creates an HTML element specified by a tag name. Here's
an example of creating a new paragraph (``) element:

Code:
const para = document.createElement("p"); //output in console
In this example, `para` is now an object representing a element.

2.Adding Text Content to the Element


Once you've created an element, you can add text content to it. You
can do this using the `innerText` or `innerHTML` property. Here's how
you can add text to the para element:

Code:
para.innerText = "This is a paragraph"; //output in console
Now, para represents a element with the text "This is a paragraph"
inside.

3. Appending the Element to the Document


After creating an element and adding content to it, you can append it
to an existing element in the HTML document using the `appendChild()`
method. Here's how you can append the `para` element to the body of
the document:
Code:
document.body.appendChild(para); // console
Now, the para element is added to the end of the document body.
Forms and Input Validation
1.Creating a Form In HTML, a form is created using the <form> tag.
Inside this tag, you can place input elements like <input>, <textarea>,
etc. Each input element should have a name attribute for identification.
Code:
HTML
<form id="myForm">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<input type="submit" value="Submit">
</form>
2.In this example, we have a form with an input field for the username
and a submit button.Form validation is the process of checking that the
data entered by the user is correct and valid. This can be done using
JavaScript.
Here’s an example of a simple validation function that checks if the
username field is empty:
Code:
function validateForm()
{
const username = document.getElementById("username").value;
if (username == "")
{
alert("Username must be filled out"); return false;
}}
3.Attaching the Validation Function to the Form:
The validation function should be called when the form is submitted.
This can be done byadding an onsubmit() attribute to the form tag.
Here’s how you can attach the validateForm function to the form:
Code:
HTML
<form id="myForm" onsubmit="return validateForm()">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<input type="submit" value="Submit">
</form>
Now, when the form is submitted, the validate Form function will be
called. If the function
returns false, the form submission will be cancelled.

Local Storage
Sure, let's break down the concept of Local Storage in JavaScript into
several steps, each with a detailed explanation and a full-fledged
example.
What is Local Storage?
Local Storage is a property that allows JavaScript sites and apps to save
key-value pairs in a web browser with no expiration date. This means
the data stored persists even after the user closes the browser or
restarts the computer. It's part of the Web Storage API and is used for
storing and retrieving data.
1.Setting Items in Local Storage
You can add data to Local Storage using the `setItem()` method. This
method takes two parameters: the key and the value
Code:
localStorage.setItem('name', 'John Doe'); //console
In this example, we're storing the string 'John Doe' under the key
'name'.
2.Getting Items from Local Storage
You can retrieve data from Local Storage using the `getItem()` method.
This method takes one parameter: the key of the data you want to
retrieve.
Here's an example:
Code:
const name = localStorage.getItem('name');
console.log(name); // Outputs: John Doe
In this example, we're retrieving the data stored under the key 'name'
and logging it to the
console.
3.Removing Items from Local Storage
You can remove data from Local Storage using the `removeItem()`
method. This method takesone parameter: the key of the data you
want to remove.
Here's an example:

Code:
localStorage.removeItem('name'); //console
In this example, we're removing the data stored under the key 'name
4.Clearing Local Storage
You can clear all data from Local Storage using the `clear()` method.
Here's an example:
Code:
localStorage.clear(); //console
This will remove all data stored in Local Storage.

Java script Objects and Properties


An object in JavaScript is a data type that can take in collections of key-
value pairs. A major difference between an object and other data types
such as strings and numbers in JavaScript is that objects can store
different types of data as its values. The key, also known as the
property name, is usually a string.
Here’s an example of creating an object:
Code:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

What are Properties in JavaScript?


The name-value pairs in JavaScript objects are called properties. The
name, also known as the property name, is usually a string.
Here’s an example of accessing properties:
Code:
console.log(person.firstName); // Outputs: John
console.log(person["lastName"]); // Outputs: Doe

Methods in JavaScript Objects:


Objects can also have methods. Methods are actions that can be
performed on objects. Methods are stored in properties as function
definitions.
Here’s an example of a method in an object:
let laptop={
brand:'hp',
price:30000,
ram:16,
greet:function(){
console.log("hello world");
}
}
laptop.greet();

Enumerating Properties:
There are several ways to list/traverse object properties in JavaScript.
One common way is using
for...in loops2.
Here’s an example of enumerating properties:

for(let key in laptop)


{
console.log(key+ ":" + laptop[key]);
}

Deleting Properties:
You can remove a non-inherited property from an object using the
delete operator
delete person.age;
console.log(person);

THIS Keyword:
This keyword is used to refer the current object
let laptop2={
brand:'hp',
price:30000,
ram:16,
cpu:'i7',
greet:function(){
console.log(laptop1.cpu);
}
}
let laptop1={
brand:'hp',
price:30000,
ram:16,
cpu:'i9',
greet:function(){
console.log(this.cpu);
}
}
laptop2.greet()

Constructor Functions
In JavaScript, a constructor function is used to create objects. A
constructor function is a special kind of function used to create and
instantiate objects, especially when multiple objects of the same kind
need to be created. A constructor defines the object properties and
methods.

Code:
function Mobile(mobilename,mobileprice,mobilecam)
{
this.mobilename=mobilename;
this.mobileprice=mobileprice;
this.mobilecam=mobilecam;

}
var m1=new Mobile("oneplus", 42000,"50mp");
var m2=new Mobile("redmi note 5",12000,"40px");
console.log(m1)
Iterating every property:

function Mobile(mobilename,mobileprice,mobilecam)
{
this.mobilename=mobilename;
this.mobileprice=mobileprice;
this.mobilecam=mobilecam;
}
var m1=new Mobile("oneplus", 42000,"50mp");
var m2=new Mobile("redmi note 5",12000,"40px");
var m3=new Mobile("redmi 5A", 5000,"30mp");
var m4=new Mobile("oppo 5A",13000,"40px");
var store=[m1,m2,m3,m4] //storing objects in array
for(x of store) // x is an object
{
for(dummy in x) //dummy is the key of object x and iterating keys of
object
{
document.write(dummy+":"+x[dummy]+"<br>")
}
}

Class in java script


Class is a blue print of an object similar to functional constructor. It has
default method with name f “constructor”, this constructor used to set
the properties of an object is created. We can create any no. of
methods in JS class
Code:
<h1>JavaScript Classes</h1>
<p>Creating two car objects from a car class:</p>

<p id="demo"></p>
<script>
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}

const myCar1 = new Car("Ford", 2014);


const myCar2 = new Car("Audi", 2019);

document.getElementById("demo").innerHTML =
myCar1.name + " " + myCar1.year;
</script>

Inheritence
Process of acquiring all functionalities of parent class from child class
<p>Use the "extends" keyword to inherit all methods from another
class.</p>
<p>Use the "super" method to call the parent's constructor
function.</p>

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

<script>
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}

class Model extends Car {


constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

const myCar = new Model("Ford", "Mustang");


document.getElementById("demo").innerHTML = myCar.show();
</script>

CallBacks
A callback in JavaScript is a function that is passed as an argument to
another function and is executed after the main function has finished
its execution. The main function is called with a callback function as its
argument, and when the main function is finished, it calls the callback
function to provide a result.
Example1:

Function hello(callback)
{
Console.log(“hello is printed”);
Callback()
}
Function leave()
{
Console.log(“leave is printed”);
}
Hello(leave);

Example2:
function myDisplayer(some) {
console.log(some);
}
function myCalculator(num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);

Why use Callbacks?


Callbacks are used to handle the results of asynchronous operations in
a non-blocking manner. The main function in the examples above is a
higher-order function because it takes a callback function as an
argument.

What is asynchronous :
Asynchronous operations are operations that take a significant amount
of time to complete.

Higher-order functions and Callbacks:


A higher-order function is a function that takes one or more functions
as arguments, or returns a function as a result. The function passed to
myCalculator in the first code example is an anonymous function.

What is a Promise?
A Promise in JavaScript is an object that represents the eventual
completion (or failure) of an asynchronous operation and its resulting
value. It’s a way to handle asynchronous operations without blocking
the rest of your code
Promise States
A Promise can be in one of three states:
Pending: The Promise is still working and hasn't been fulfilled or
rejected yet.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.

A Promise is created using the Promise constru

ctor, which takes a callback function as its argument. This callback


function takes two arguments: resolve and reject, which are both
functions. Here’s the syntax:
Code:
let myPromise = new Promise(function(myResolve, myReject) {
// "Producing Code" (May take some time)
myResolve(); // when successful
myReject(); // when error
});

Example code:
let mypromise=new Promise(function(resolve,reject){
let x=0;
if(x==0){
resolve("ok")
}
else{
reject("error");
}
})

Here x has 2 different states fullfill and reject. To handle those states
we need to use following methods then(), catch(), finally().
Then(): used to handle the promise when it is success or resolved
Catche():used to handle the promise when it is rejected.
Finally():used to execute the block of code with irrespective of result.

Code:
mypromise.then(
function(value) { console.log(value); }, // Success

);
mypromise.catch(
function(error) { console.log(error); },
);
mypromise.finally(
function(){console.log("promise completed")}
)

Timing functions:
Timing function in js used to execute a function in specific time intervals
or delay the execution of a function time intervals or delay the
execution of a function for specific time.
1.setTimeOut:used to delay the execution of a fun for specific time.
Syntax: setTimeOut(fun,millisecond)
2.setInterval:used to execute a fun at specific time intervals.
Syntax: setInerval(fun(){funname()},milliseconds)

Async Keyword
The async keyword can be placed before a function. This means the
function will always return a Promise. If the function returns a value
that is not a Promise, JavaScript automatically wraps it in a resolved
Promise.

Await Keyword
The await keyword can only be used inside an async function. It makes
the function pause and wait for the Promise to resolve or reject, then
resumes the execution and returns the resolved value.
Here’s an example:
Code:
async function myFunction() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("done!"), 5000)
});
let result = await promise; // wait until the promise resolves
alert(result); // "done!"
}
myFunction();

Fetch API in JS:


>Fetch method used to consume the data from REST API. It returns
data in JSON format XML format of data
>Fetch method has only one parameter that is URL of the REST API
>JS only follows JSON format(key value based) works with REST API
because it supports JSON and XML

Code:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((res)=>res.json())
.then((data)=>{
console.table(data)
})

Error Handling in Asynchronous Code

Error Handling in Callbacks


In JavaScript, a common way to handle errors in asynchronous code
that uses callbacks is through the use of error-first callbacks. In this
convention, the first argument passed to the callback function is an
error object. If there is no error, the error object is null.
Here’s an example:
Code:
const mod = (a, b, callback) => {
setTimeout(() => {
if (b == 0) {
callback("Modulo zero is not allowed");
} else {
callback(null, a % b);
}
}, 0);
};
mod(5, 2, (err, res) => {
if (err) {
console.log(err);
} else {
console.log('The result is ' + res);
}
});
mod(5, 0, (err, res) => {
if (err) {
console.log(err);
} else {
console.log(`The result is ${res}`);
}
});
In this example, if b is 0, an error is passed to the callback. Otherwise,
the result of the modulo
operation is passed.

Error Handling in async and await:


To handle errors in Async/Await, you can use a try/catch block.
Here’s an example:
Code:
async function myFunction() {
try {
let response = await fetch('https://no-such-url');
} catch(err) {
alert(err); // TypeError: failed to fetch
}
}
myFunction();
In this example, the fetch Promise rejects with an error, the catch block
is triggered and handles
the error
Responsive Web Design Principles

Sure, here's some detailed information about Responsive Web Design


Principles:

Responsive Web Design


Responsive Web Design (RWD) is a web design approach that makes
web pages render well on all screen sizes and resolutions while
ensuring good usability¹. It is the way to design for a multi-device web¹.

Key Principles of Responsive Web Design

Fluid Layouts:
With a fluid layout, you can create web pages that adapt to the current
viewport width and height². Common practice includes using the `max-
width` property instead of giving a fixed width to an element². Also,
using percentage (`%`), viewport height (`vh`), or viewport width (`vw`)
helps improve adaptability that is not possible with pixels (`px`).

Responsive Units:
As you move to more advanced CSS, you’ll often see the use of `rem`
and `em` units for length instead of `px` units². This is because the
`rem` unit makes it super easy to scale the entire layout.
Flexible Images
Images are a prime concern while designing even the most basic layout.
You always have to take care to size them properly so that they fit the
design. Also, by default, they don’t scale with changes in the viewport.
So, you should use `%` for the dimensions of your images, along with
the `max-width` property.

Media Queries:
You can bring responsive sites to life by using media queries. Fluid grids
are good to start with, but you’ll find that there are a few points where
the layout starts to break down. Adding breakpoints for these viewport
widths tunes the layout for different devices.

19.Media Queries for Different Devices


Media Queries
Media queries are a CSS technique introduced in CSS3¹. They use the
`@media` rule to include a block of CSS properties only if a certain
condition is true¹. For example, if the browser window is 600px or
smaller, the background color will be lightblue¹:
css
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
Breakpoints

You can add a breakpoint where certain parts of the design will behave
differently on each side of the breakpoint¹. For instance, when the
screen (browser window) gets smaller than 768px, each column should
have a width of 100%¹:

```css
@media only screen and (max-width: 768px) {
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
}
Mobile First
Mobile First means designing for mobile before designing for desktop
or any other device¹. This will make the page display faster on smaller
devices¹. This means that we must make some changes in our CSS¹:
css
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
@media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {width: 8.33%;}
.col-2 {width: 16.66%;}
.col-3 {width: 25%;}
.col-4 {width: 33.33%;}
.col-5 {width: 41.66%;}
.col-6 {width: 50%;}
.col-7 {width: 58.33%;}
.col-8 {width: 66.66%;}
.col-9 {width: 75%;}
.col-10 {width: 83.33%;}
.col-11 {width: 91.66%;}
.col-12 {width: 100%;}
}
```

Multiple Breakpoints
You can add as many breakpoints as you like¹. For instance, you can add
one more media query (at 600px), and a set of new classes for devices
larger than 600px (but smaller than 768px)¹:
```css
@media only screen and (min-width: 600px) {
/* For tablets: */
.col-s-1 {width: 8.33%;}
.col-s-2 {width: 16.66%;}
.col-s-3 {width: 25%;}
.col-s-4 {width: 33.33%;}
.col-s-5 {width: 41.66%;}
.col-s-6 {width: 50%;}
.col-s-7 {width: 58.33%;}
.col-s-8 {width: 66.66%;}
.col-s-9 {width: 75%;}
.col-s-10 {width: 83.33%;}
.col-s-11 {width: 91.
20.Introduction to the Bootstrap Framework and Its Grid System.

Sure, here's a detailed introduction to the Bootstrap Framework and its


Grid System:
Bootstrap Framework:
Bootstrap is a popular web development framework that allows
developers to build responsive, mobile-first websites quickly and
efficiently³⁴. It provides pre-designed components, CSS styles, and
JavaScript plugins that can be used to create modern web applications³.

Grid System:
The grid system is a key feature of Bootstrap. It's a flexible, mobile-first
layout system built with flexbox that's fully responsive¹. It's based on a
12-column layout, which can be customized to suit the needs of the
website³⁴.

Here's how the grid system works:


Containers:
Containers provide a means to center and horizontally pad your site's
contents. Use `.container` for a responsive pixel width or `.container-
fluid` for width: 100% across all viewport and device sizes¹.

Rows:
Rows are wrappers for columns. Each column has horizontal padding
(called a gutter) for controlling the space between them. This padding is
then counteracted on the rows with negative margins¹.

Columns:
In a grid layout, content must be placed within columns and only
columns may be immediate children of rows. Thanks to flexbox, grid
columns without a specified width will automatically layout as equal
width columns¹.
Here's an example of how to use the grid system:

html
<div class="container">
<div class="row">
<div class="col-sm"> One of three columns </div>
<div class="col-sm"> One of three columns </div>
<div class="col-sm"> One of three columns </div>
</div>
</div>
In this example, three equal-width columns are created on small,
medium, large, and extra-large devices using predefined grid classes¹.
To make the grid responsive, there are five grid breakpoints, one for
each responsive breakpoint: all breakpoints (extra small), small,
medium, large, and extra large¹.
Frame work:frame work is set of advaced features which is developed
by using core language
BOOT STRAP:
Frame work:frame work is set of advaced features which is developed
by using core language
BOOT STRAP:
Boot strap is the most popular HTML CSS and JS framework for
developing responsive mobile first projects on web
Boot strap overview:
>includes HTML CSS based design templates for forms,buttons tables
navigation images carousels and many others
>user increasingly accessing website from a verity of devices
media queries:
media queries used to responsive website with CSS here we can apply
some styles based on the user screen size

syntax:
@media(min-width:500px){
//css style customized for desktop
}

Grid system:
>writing meta tag to read the device width
>importing BS to our page
cdnjs>search for bootstrap>select link
bootstrap.min.css,bootstrap.bundle.min.js
Grid system:
>writing meta tag to read the device width
>importing BS to our page

Text formating in BS:


colors used in BS
color:text-success(green)
-danger(red)
-primary(blue)
-secondary(gray)
-white(white)
-warning(yellow)
info(powderblue)
trasnforming:text-uppercase/lowercase
background:bg-success/bg-primary/danger/warning/info/warning/
white

images:
img-fluid/img-thumbnail/img-rounded/img-circle
buttons:
btn btn-success/btn
btn-primary/danger/info/warning/white/secondary
navigation bar code in BS
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<a href="" clas="navbar-brand"></a>
<div class="container-fluid">
<div class="col-md-5">
<button class="navbar-toggler" data-bs-toggle="collapse" data-
bs-target="#mynav">
<span class="navbar-toggler-icon"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="mynav">
<ul class="navbar-nav">
<li class="nav-item"><a href="sample.html" class="active nav-
link">Sample</a></li>
<li class="nav-item"><a href="home.html" class="nav-
link">home</a></li>
<li class="nav-item"><a href="about.html" class="nav-
link">about</a></li>
<li class="nav-item"><a href="contact.html" class="nav-
link">contact</a></li>
</ul>
</div>
</div>
</nav>

CAROUSEL CODE:
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="carousel slide" data-bs-ride="carousel" id="mycar">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="cricket.jpg" class="img-fluid">
</div>
<div class="carousel-item">
<img src="tree.jpg" class="img-fluid" >
</div>
<div class="carousel-item">
<img src="tree.jpg" class="img-fluid">
</div>
<div clas="carousel-item">
<img src="image.jpg" class="img-fluid">
</div>
</div>
<a href="" data-bs-target="#mycar" class="carousel-control-
prev" data-bs-slide="prev">
<span class="carousel-control-prev-icon"></span>
</a>
<a href="" data-bs-target="#mycar" class="carousel-control-
next" data-bs-slide="next">
<span class="carousel-control-next-icon"></span>
</a>
</div>
</div>
</div>

CARDS IN BOOTSTRAP
<div class="col-md-3">
<div class="card">
<img src="ambedkar.jpg" class="card-img-top">
<div class="card-body">
<h1>Ambedker</h1>
<p>Bhimrao Ramji Ambedkar was an Indian jurist, economist,
social reformer and political leader who headed the committee drafting
the Constitution of India ...</p>
<div class="card-footer">
<button class="btn btn-info">click me</button>
</div>
</div>
</div>
</div>

FORMS IN BOOTSTRAP:
<div class="container-fluid">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="form-group">
<label for="" class="form-label">Enter user name</label>
<input type="text" class="form-control">
</div>
<div class="form-group">
<label for="" class="form-label">enter password</label>
<input type="password" class="form-control">
</div>
<div class="form-group">
<label for="" class="form-label">enter mobile number</label>
<input type="number" class="form-control">
</div>
</div>
</div>
</div>

https://meet.jit.si/SuperiorConferencesApproachAnnually
https://meet.jit.si/LatterAgentsHuntLittle

You might also like