0% found this document useful (0 votes)
7 views55 pages

CSS and JavaScript Basics Guide

This document covers Module 2 of a web programming course, focusing on CSS and JavaScript. It includes an introduction to CSS syntax, selectors, and properties, as well as JavaScript fundamentals such as functions, arrays, and the Document Object Model (DOM). The document also outlines assignments and tutorials related to creating web pages and using CSS for styling and layout.

Uploaded by

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

CSS and JavaScript Basics Guide

This document covers Module 2 of a web programming course, focusing on CSS and JavaScript. It includes an introduction to CSS syntax, selectors, and properties, as well as JavaScript fundamentals such as functions, arrays, and the Document Object Model (DOM). The document also outlines assignments and tutorials related to creating web pages and using CSS for styling and layout.

Uploaded by

jiji
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Dept.

of CSE ICCSCEM

Module -2 (CSS, JavaScript)

Introduction to Stylesheets : Introduction to CSS-Basic syntax and structure-Inline


Styles, Embedded Style Sheets, Conflict Resolution, Linking External Style Sheets-
Exploring CSS Selectors-Properties, values, Positioning Elements: Absolute Positioning,
Relative Positioning -Backgrounds-List Styles-Element Dimensions- Table Layouts-Box
Model and Text Flow-div and span -Basics of Responsive CSS, Media port & Media
Queries.

Introduction to Javascript: Introduction to Scripting- Programming fundamentals of


Javascript- Obtaining User input with prompt Dialogs-Arithmatic-Decision Making-
Control Statements-Functions-Arrays-Objects-Document Object Model(DOM)-Form
Processing

Assignment 2:

1 Write html code to align an image using css CO2 K3 2 Write examples for
javascript object creation using CO2 K3 a. object literal
b. instance of object
c. object constructor

Tutorial 2:

1. Develop a web page as follows: CO2 K3


Sl No Name Age <image>

1 Abc 23 <image of Abc>

2 Pqr 30 <image og pqr>

2. Write a javascript to return the day CO2 K3


Dept. of CSE ICCSCEM

MODULE 2

INTRODUCTION TO 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 style sheets are stored in CSS files

CSS Syntax

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.
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)
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:

2
CST 463 Web Programming

Dept. of CSE ICCSCEM


OUTPUT:

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":

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. The CSS Universal
Selector
The universal selector (*) selects all HTML elements on the page.

3
CST 463 Web Programming
Dept. of CSE ICCSCEM
The CSS Grouping Selector
The grouping selector selects all the HTML elements with the same style definitions. Look
at the following CSS code (the h1, h2, and p elements have the same style definitions):

It will be better to group the selectors, to minimize the code. To group selectors, separate each selector
with a comma.

4
CST 463 Web Programming
Dept. of CSE ICCSCEM

How To Add CSS In HTML


When a browser reads a style sheet, it will format the HTML document according to the information in
the style sheet.
Three Ways to Insert CSS. There are three ways of inserting a style sheet:

External CSS
Internal CSS
Inline CSS
Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain any
CSS property.

Internal CSS
An internal style sheet may be used if one single HTML page has a unique style. The internal style
is defined inside the <style> element, inside the head section.

5
CST 463 Web Programming
Dept. of CSE ICCSCEM
External CSS

With an external style sheet, you can change the look of an entire website by changing just
one file!
Each HTML page must include a reference to the external style sheet file inside the

<link>element, inside the head section.


An external style sheet can be written in any text editor, and must be saved with a .css
extension. The external .css file should not contain any HTML tags. Here is how the
"[Link]" file looks:

6
CST 463 Web Programming
Dept. of CSE ICCSCEM

COLORS

CSS uses color values to specify a color. Typically, these are used to set a color either for the foreground
of an element or else for the background of the element. They can also be used to affect the color of
borders and other decorative effects. You can specify your color values in various formats.

CSS Colors - Hex Codes

A hexadecimal is a 6 digit representation of a color. The first two digitsRR represent a red value, the next
two are a green valueGG, and the last are the blue valueBB. A hexadecimal value can be taken from any
graphics software like Adobe Photoshop, Jasc Paintshop Pro, or even using Advanced Paint Brush. Each
hexadecimal code will be preceded by a pound or hash sign '#'. Following are the examples to use
Hexadecimal notation.

Ex: #FFFF00
CSS Colors - RGB Values
This color value is specified using the rgb property. This property takes three values, one each for red,
green, and blue. The value can be an integer between 0 and 255 or a percentage.

NOTE: All the browsers does not support rgb property of color so it is recommended not to use it.
Ex: rgb255, 0, 255

CSS Colors - RGBA Values

This color value is specified using the rgba(red,green,blue,alpha) [Link] alpha value which
represents opacity—can be any value in the range 0.0(fully transparent) through 1.0(fully opaque).

Ex: rgba(255,0,0,0.5)

CSS Colors – HSL/HSLA Values

HSL (hue,saturation,lightness)
7
CST 463 Web Programming
Dept. of CSE ICCSCEM
HSLA(hue,saturation,lightness,alpha)

The hue is a color or shade expressed as a value from 0 to 359 representing the degree on a color
[Link] colors on the wheel progress in the ode of the colors of the rainbow.
The saturation- the intensity of the hue is expressed as a percentage,where 100% is fully saturated and
0% is gray.
Lightness- the intensity of light or luminance of the hue

CSS Background Color

CSS Text Color

FONT PROPPERTIES

The font property is a shorthand property for:


font-style
font-variant
font-weight
font-size/line-height
font-family

The font-family property specifies the font for an element.


The font-size property sets the size of a font.
Eg:
div.a {
font-size: 15px;
}
div.b {

8
CST 463 Web Programming
Dept. of CSE ICCSCEM
font-size: large;
}
div.c {
font-size: 150%;
}

■ The font-style property specifies the font style for a


text. Eg:
{
font-style: normal;
}
{
font-style: italic;
}

{
font-style: oblique;
}

Layout and Positioning

position property

9
CST 463 Web Programming
Dept. of CSE ICCSCEM
The position property determines which of the positioning schemes is used to calculate the
position of a box. Values other than static make the box a positioned box, and cause it
to establish an absolute positioning containing block for its descendants. Values have
the following meanings:
static: The box is not a positioned box, and is laid out according to the rules of its parent formatting
context. The inset properties do not apply.
relative: The box is laid out as for static, then offset from the resulting position. This offsetting is a purely
visual effect, and does not affect the size or position of any other box, except insofar as it increases the
scrollable overflow area of its ancestors. This positioning scheme is called relative positioning.
Sticky: Identical to relative, except that its offsets are properties) in whichever axes
automatically adjusted in reference to the nearest ancestor the inset properties are not both auto, to try to keep the box
scroll container’s scrollport (as modified by the inset in view within its containing block as the user scrolls. This
positioning scheme is called sticky positioning.

absolute: The box is taken out of flow such that it has no impact on the size or position of its siblings and
ancestors, and does not participate in its parent’s formatting context.
Instead, the box is positioned and sized solely in reference to its absolute positioning containing
block, as modified by the box’s inset properties, see § 4 Absolute Positioning Layout Model. It
can overlap in-flow content or other absolutely positioned elements, and is included in the
scrollable overflow area of the box that generates is containing block. This positioning scheme is
called absolute positioning.
fixed: Same as absolute, except the box is positioned and sized relative to a fixed positioning containing
block (usually the viewport in continuous media, or the page area in paged media). The box’s position is
fixed with respect to this reference rectangle: when attached to the viewport it does not move when the
document is scrolled, and when attached to the page area is replicated on every page when the document
is paginated. This positioning scheme is called fixed positioning and is considered a subset of absolute
positioning.
The precise location of a positioned box is controlled by the inset properties: the physical inset
properties top, right, bottom, left; the flow-relative inset properties inset block-start, inset-inline-
start, inset-block-end,and inset-inline-end; and their shorthands, inset-block, inset-inline, and inset.
The interpretation of these inset properties varies by positioning scheme:
● for absolute positioning, they represent insets from the containing block.
● for relative positioning, they represent insets from the box’s original margin edge.
● for sticky positioning, they represent insets from the scrollport edge.
Relative Positioning

For a relatively positioned box, the inset properties move the box inward from the
respective edge, without changing its size. left moves the box to the right, right
moves it to the left, etc. Since boxes are not split or stretched as a result of relative
positioning opposing used values in a given axis must be negations of each other:

10
CST 463 Web Programming
Dept. of CSE ICCSCEM

● If opposing inset properties in an axis both compute to auto (their initial values),
their used values are zero (i.e., the boxes stay in their original position in that axis).
● If only one is auto, its used value becomes the negation of the other, and the box is
shifted by the specified amount.
● If neither is auto, the position is over-constrained; (with respect to the writing mode
of its containing block) the computed end side value is ignored, and its used value
becomes the negation of the start side.
Sticky positioning

Sticky positioning is similar to relative positioning except the offsets are


automatically calculated in reference to the nearest scrollport.

For a sticky positioned box, the inset properties represent insets from the respective
edges of the nearest scrollport, defining the sticky view rectangle used to constrain
the box’s position. (For this purpose an auto value represents a zero inset.) If this
results in a sticky view rectangle size in any axis less than the size of the border box
of the sticky box in that axis, then the effective end-edge inset in the affected axis is
reduced (possibly becoming negative) to bring the sticky view rectangle’s size up
to the size of the border box in that axis (where end is interpreted relative to the
writing mode of the containing block).
Absolute (and Fixed) Positioning
For an absolutely positioned box, the inset properties effectively reduce the
containing block into which it is sized and positioned by the specified amounts.
If only one inset property in a given axis is auto, it is set to zero. If both inset
properties in a given axis are auto, then, depending on the box’s self-alignment
property in the relevant axis (treating normal as start and any distributed, baseline,
or stretch alignment value as its fallback alignment):

11
CST 463 Web Programming
Dept. of CSE ICCSCEM

● for self-start alignment or its equivalent Set its start-edge inset property to the static position,
and its end-edge inset property to zero.
● for self-end alignment or its equivalent Set its end-edge inset property to the static position, and
its start-edge inset property to zero.
● for center alignment Let start distance be the distance from the center of its static position
rectangle to the start edge of its containing block, and end distance be the distance from the
center of its static position rectangle to the end edge of its containing block. If start distance is
less than or equal to end distance, then set the start-edge inset property to zero, and set the
end-edge inset property to (containing block size - 2 × |start distance|); otherwise, set the end-
edge inset property to zero and the start-edge inset property to (containing block size - 2 × |end
distance|)

If these adjustments result in an effective containing block size in any axis less than
zero, then the weaker inset in the affected axis is reduced (possibly becoming negative) to
bring that size up to zero. In the case that only one inset is auto, that is the weaker inset;
otherwise the weaker inset is the inset of the end edge (where end is interpreted relative to
the writing mode of the containing block).

If its self-alignment property in an axis is normal, then the resolved value of its
weaker inset in that axis is the value necessary to match that edge of its inset-modified
containing block to the corresponding edge of its margin box after layout.

Block Layout
The static position rectangle is a zero-thickness rectangle spanning between the
inline-axis sides of the box’s static-position containing block; and positioned at its block
start static position.
Inline Layout
The static position rectangle is a zero-thickness rectangle spanning between the
line- over/line-under sides of the line box that would have contained its “hypothetical box”;
and positioned at its inline-start static position.
Flex Layout
The static position rectangle of the child of a flex container corresponds to the
content edges of the flex container.
Grid Layout
By default, the static position rectangle of the child of a grid container corresponds
to the content edges of the grid container. However, if that grid container also establishes
the box’s actual containing block, then the grid area specified by the grid-placement
properties establishes its static position rectangle instead.
For the purposes of calculating the static position rectangle, the containing block of
fixed positioned elements is the initial containing block instead of the viewport, and all
scroll containers should be assumed to be scrolled to their initial scroll position.
Additionally, all auto margins on the box itself are treated as zero.

12
CST 463 Web Programming
Dept. of CSE ICCSCEM

Eg:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>cell padding</title>
5. <style>
6. div {
7. width: auto;
8. text-align: center;
9. padding: 15px;
10. border: 3px solid red
11. }
12. img {
13. max-width: 100%;
14. height: auto;
15. }
16. </style>
17. </head>
18. <body>
19. <div>
20. <img src= "[Link]">
21. </div>
22. </body>
23. </html>

13
CST 463 Web Programming
Dept. of CSE ICCSCEM

Output
How to align images in CSS?
Images are an important part of any web application. Including a lot of images in a web
application is generally not recommended, but it is important to use the images wherever they
required. CSS helps us to control the display of images in web applications.
Aligning an image means to position the image at center, left and right. We can use the float
property and text-align property for the alignment of images.
If the image is in the div element, then we can use the text-align property for aligning the
image in the div.
Example
In this example, we are aligning the images by using the text-align property. The images are
in the div element
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. div {
6. border: 2px solid
red; 7. }
8. img{
9. height: 250px;
10. width: 250px;

14
CST 463 Web Programming
Dept. of CSE ICCSCEM

11. }
12. #left {
13. text-align: left;
14. }
15. #center {
16. text-align: center;
17. }
18. #right{
19. text-align: right;
20. }</style>
21. </head>
22. <body>
23. <div id ="left">
24. <img src="[Link]">
25. </div>
26. <div id ="center">
27. <img src="[Link]">
28. </div>
29. <div id ="right">
30. <img src="[Link]">
31. </div>
32. </body>
33. </html>

15
CST 463 Web Programming
Dept. of CSE ICCSCEM

Output
CSS helps us to control the display of images in web applications. The centering of images
or texts is a common task in CSS. To center an image, we have to set the value of margin- left and
margin-right to auto and make it a block element by using the display: block; property.
If the image is in the div element, then we can use the text-align: center; property for
aligning the image to center in the div.
The <img> element is said to be an inline element that can easily be centered by applying
the text-align: center; property of CSS to the parent element that contains it.
We can use the shorthand property margin and set it to auto for aligning the image at the
center, rather than using the margin-left and margin-right property.
Let's see how to center an image by applying text-align: center; property to its parent
element.
Example
In this example, we are aligning the images by using the text-align: center; property. The
image is in the div element.
How to center images in CSS?

1. <!DOCTYPE html>

2. <html>
3. <head>
4. <style>
5. div {
6. border: 2px solid
red; 7. }

16
CST 463 Web Programming
Dept. of CSE ICCSCEM

8. img{
9. height: 300px;
10. width: 300px;
11. }
12. #center {
13. text-align: center;
14. }
15. </style>
16. </head>
17. <body>
18. <div id ="center">
19. <img src="[Link]">
20. </div>
21. </body>
22. </html>
Output

17
CST 463 Web Programming
Dept. of CSE ICCSCEM

How to add background image in CSS?


The background-image property in CSS is used to set an image as the background of an
element. Using this CSS property, we can set one or more than one background image for an
element.
By default, the image is positioned at the top-left corner of an element and repeated both
horizontally as well as vertically. The background image should be chosen according to the text
color. The bad combination of text and background image may be a cause of poorly designed
and not readable webpage.

The url() value of this property allows us to include a file path to any image. It will show the
element's background. We can use multiple images or a mixture of gradients and images for the
background. If the background-image is failed to load or if we are using the gradients, but they
are not supported on the corresponding browser then, we can use the fallback value (the value
used as the substitution) as the background color of the element.
Syntax
background-image: url();
Values
url(): It is the URL to the image. We can separate the URLs by a comma if we want to specify
more than one image.
Example:

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. body {
6. background-image: url("[Link]");
7. background-c
olor: lightgray; 8. }
9. </style>

18
CST 463 Web Programming
Dept. of CSE ICCSCEM

10. </head>
11. <body>
12. </body>
13. </html>
Output

CSS Gradient
CSS gradient is used to display smooth transition within two or more specified colors.

Why CSS Gradient


These are the following reasons to use CSS gradient.

o You don't have to use images to display transition effects.


o The download time and bandwidth usage can also be reduced.
o It provides better look to the element when zoomed, because the gradient is generated by the
browser.

There are two types of gradient in CSS3.

19
CST 463 Web Programming
Dept. of CSE ICCSCEM

1. Linear gradients
2. Radial gradients
3. CSS Linear Gradient
.
The CSS3 linear gradient goes up/down/left/right and diagonally. To create a CSS3 linear
gradient, you must have to define two or more color stops. The color stops are the colors which are
used to create a smooth transition. Starting point and direction can also be added along with the
gradient effect.
CSS Radial Gradient

You must have to define at least two color stops to create a radial gradient. It is defined by its
center.

Media Queries

Media queries are a way to target browser by certain characteristics, features, and user
preferences, then apply styles or run other code based on those things. Perhaps the most common
media queries in the world are those that target particular viewport ranges and apply custom styles,
which birthed the whole idea of responsive design.
There are lots of other things we can target beside viewport width. That might be screen
resolution, device orientation, operating system preference, or even more among a whole bevy of
things we can query and use to style content

20
CST 463 Web Programming
Dept. of CSE ICCSCEM

INTRODUCTION TO JAVASCRIPT

JavaScript is a programming language we can use to make a website interactive. When we


search something on Google or click a link, our website changes — that’s what JavaScript
allows us to do.
JavaScript is used to create client-side dynamic pages.
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code for the web
browser.
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which is used by several
websites for scripting the webpages. It is an interpreted, full-fledged programming language
that enables dynamic interactivity on websites when applied to an HTML document. It was
introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator
browser. Since then, it has been adopted by all other graphical web browsers. With JavaScript,
users can build modern web applications to interact directly without reloading the page every
time. The traditional website uses js to provide several forms of interactivity and simplicity.
Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In
addition to web browsers, databases such as CouchDB and MongoDB uses JavaScript as their
scripting and query language.
Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in


execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

21
CST 463 Web Programming
Dept. of CSE ICCSCEM

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.
JavaScript Example
1. <script>
2. [Link]("Hello JavaScript by JavaScript");
3. </script>

JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily interpret the
code.
The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.
Advantages of JavaScript comments
There are mainly two advantages of JavaScript comments.
1. To make code easy to understand It can be used to elaborate the code so that end user
can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may
be need to disable the code. In such case, it is better to use comments.

Types of JavaScript Comments

There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

JavaScript Single line Comment

It is represented by double forward slashes (//). It can be used before and after the statement.
Let’s see the example of single-line comment i.e. added before the statement.

22
CST 463 Web Programming
Dept. of CSE ICCSCEM

1. <script>
2. // It is single line comment
3. [Link]("hello javascript");
4. </script>
JavaScript Multi line Comment
It can be used to add single as well as multi line comments. So, it is more convenient. It is
represented by forward slash with asterisk then asterisk with forward slash. For example: 1. /*
your code here */

It can be used before, after and middle of the statement.


1. <script>
2. /* It is multi line comment.
3. It will not be displayed */
4. [Link]("example of javascript multiline comment");
5. </script>
JavaScript Variable

A JavaScript variable is simply a name of storage location. There are two types of variables
in JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers). 1.

Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign. 2.

After first letter we can use digits (0 to 9), for example value1.

3. JavaScript variables are case sensitive, for example x and X are different variables.

Correct JavaScript variables

1. var x = 10;
2. var _value="sonoo";

Incorrect JavaScript variables 1.

var 123=30;
2. var *aa=320;

23
CST 463 Web Programming
Dept. of CSE ICCSCEM

Example of JavaScript variable

Let’s see a simple example of JavaScript variable.

1 <script>
2 var x = 10;
3 var y = 20;
4 var z=x+y;
5 [Link](z);
6. </script>
Output of the above example

24
CST 463 Web Programming
Dept. of CSE ICCSCEM

Javascript Data Types

JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:
1. var a=40;//holding number
2. var b="Rahul";//holding string

JavaScript primitive data types

There are five types of primitive data types in JavaScript. They are as follows: String represents
sequence of characters e.g. "hello"
Undefined
Number

Boolean
represents numeric values e.g. 100 represents boolean value

either false or true represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:

25
CST 463 Web Programming
Dept. of CSE ICCSCEM Object represents instance through which we can access members

Array
represents group of similar values represents regular

RegExp expression
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. For example:
1. var sum=10+20;
Here, + is the arithmetic operator and = is the assignment
operator. There are following types of operators in
JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

Operator Description Example + Addition 10+20 = 30

Division 20/10 = 2
- Modulus (Remainder) 20%10 = 0
* Increment var a=10; a++; Now a = 11

++

Subtraction 20-10 = 10

Multiplication 10*20 = 200 26


CST 463 Web Programming
Dept. of CSE ICCSCEM

--
Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators

The JavaScript comparison operator compares the two operands. The comparison operators are as
follows:
== Is equal to 10==20 = false

=== Identical (equal and of same type)

!= Not equal to

!== Not Identical

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

JavaScript Bitwise Operators


10==20 = false 10!=20 = true 20!==20 = false 20>10 = true
20>=10 = true 20<10 = false 20<=10 = false
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

27
CST 463 Web Programming
Dept. of CSE ICCSCEM
^

<<

>>

>>>

Bitwise XOR (10==20 ^ 20==33) = false Bitwise NOT (~10) = -10 Bitwise

Left Shift (10<<2) = 40 Bitwise Right Shift (10>>2) = 2 Bitwise Right

Shift with Zero (10>>>2) = 2


28
CST 463 Web Programming
Dept. of CSE ICCSCEM

JavaScript Logical Operators

The following operators are known as JavaScript logical operators.

&& Logical AND (10==20 && 20==33) = false

||
Logical OR (10==20 || 20==33) = false Logical Not !
!
(10==20) = true

JavaScript Assignment Operators

The following operators are known as JavaScript assignment operators.

= Assign 10+10 = 20
%=
+=

-= Add and assign var a=10; a+=20; Now a = 30 Subtract and


*= assign var a=20; a-=10; Now a = 10 Multiply and assign var
/= a=10; a*=20; Now a = 200 Divide and assign var a=10; a/=2;
Now a = 5 Modulus and assign var a=10; a%=2; Now a = 0
29
CST 463 Web Programming
Dept. of CSE ICCSCEM

JavaScript Special Operators

The following operators are known as JavaScript special operators.

(?:) Conditional Operator returns value based on the condition. It is like if-else.

Comma Operator allows multiple expressions to be evaluated


,
as single statement. Delete Operator deletes a property from
Delete
the object.
In
In Operator checks if object has the given property
Instanceof
checks if the object is an instance of given type
New
creates an instance (object)
Typeof
checks the type of object.
Void
it discards the expression's return value.
Yield
checks what is returned in a generator by the generator's
iterator.

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Advantage of JavaScript function
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.
30
CST 463 Web Programming
Dept. of CSE ICCSCEM

JavaScript Function Syntax

The syntax of declaring function is given below.

1. function functionName([arg1, arg2, ...argN]){


2. //code to be
executed
3. }

JavaScript Functions can have 0 or more


arguments. JavaScript Function Example

Let’s see the simple example of function in JavaScript that does not has arguments.

1. <script>
2. function msg(){
3. alert("hello! this is
message"); 4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments

We can call function by passing arguments. Let’s see the example of function that has one
argument.

1. <script>
2. function getcube(number){
3. alert(number*number*num
ber);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
31
CST 463 Web Programming
Dept. of CSE ICCSCEM

Function with Return Value


We can call function that returns a value and use it in our program. Let’s see the example
of function that returns value.
1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r
u?"; 4. }
5. </script>
6. <script>
7. [Link](getInfo());
8. </script>
JavaScript Function Object
In JavaScript, the purpose of Function constructor is to create a new Function object. It
executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax

1. new Function ([arg1[, arg2[, argn]],] functionBody)

Parameter

arg1, arg2, , argn - It represents the argument used by function.

functionBody - It represents the function definition.


32
CST 463 Web Programming
Dept. of CSE ICCSCEM

JavaScript Function Methods


Let's see function methods with description.

apply() It is used to call a function contains this value and a single array of arguments.

bind()
It is used to create a new function.
call()
It is used to call a function contains this value and an
toString() argument list. It returns the result in a form of a string.

JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript. JavaScript is
template based not class based. Here, we don't create class to get the object. But, we direct
create objects.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

1. object={property1:value1,property2:value2. propertyN:valueN}

As you can see, property and value is separated by : (colon).


Let’s see the simple example of creating object in
JavaScript.
1. <script>
2. emp={id:102,name:"Shyam Kumar",salary:40000}
3. [Link]([Link]+" "+[Link]+" "+[Link]);
4. </script>
Output of the above example
33
CST 463 Web Programming
Dept. of CSE ICCSCEM

2) By creating instance of Object

The syntax of creating object directly is given below:

1. var objectname=new Object();

Here, new keyword is used to create object.


Let’s see the example of creating object directly.
1. <script>
2. var emp=new
Object(); 3. [Link]=101;
4. [Link]="Ravi Malik";
5. [Link]=50000;
6. [Link]([Link]+" "+[Link]+" "+[Link]);
7. </script>

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can be assigned
in the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

1. <script>
2. function emp(id,name,salary){
3. [Link]=id;
4. [Link]=name;
5. [Link]=sa
lary; 6. }

7. e=new emp(103,"Vimal Jaiswal",30000);


8.
9. [Link]([Link]+" "+[Link]+" "+[Link]);
34
CST 463 Web Programming
Dept. of CSE ICCSCEM

10. </script>

The .length property returns the length of an array.

Output of the above example

1) JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

1. var arrayname=new Array();

Here, new keyword is used to create instance of array.


Let's see the example of creating array directly.
1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] =
"John"; 7.
8. for (i=0;i<[Link];i++){
9. [Link](emp[i] + "<br>");
10. }
11. </script>
Output of the above example

35
CST 463 Web Programming
Dept. of CSE ICCSCEM

2) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we
don't have to provide value explicitly.

The example of creating object by array constructor is given below.

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<[Link];i++){
4. [Link](emp[i] +
"<br>"); 5. }
6. </script>
Output of the above example

JavaScript Array Methods


Let's see the list of JavaScript array methods with their description.

concat() It returns a new array object that contains two or more merged arrays.

It copies the part of the given array with its own elements
copywithin() and returns the modif array.

It creates an iterator object and a loop that iterates over each


entries() key/value pair.
every() It determines whether all the elements of an array are
satisfying the provided funct conditions.

36
CST 463 Web Programming
Dept. of CSE ICCSCEM
It maps all array elements via mapping function, then flattens
the result into a n array.
flat()
It fills elements into an array with static values.
flatMap() It creates a new array carrying the exact copy of another
array element.
fill() It returns the new array containing the elements that pass the
provided funct conditions.
from()
It returns the value of the first element in the given array that
filter() satisfies the specif condition.
It returns the index value of the first element in the given
array that satisfies specified condition.
find()
It invokes the provided function once for each element of an
findIndex() array. It checks whether the given array contains the
specified element.
forEach()

includes() It searches the specified element in the given array and


returns the index of the f match.
indexOf() It tests if the passed value ia an array.
It joins the elements of an array as a string.
isArray()
It creates an iterator object that contains only the keys of the
join() array, then loops through these keys

keys() It searches the specified element in the given array and


returns the index of the match.

lastIndexOf() It calls the specified function for every array element and
returns the new array

map() It creates a new array from a variable number of arguments,


holding any type argument.
of()
It removes and returns the last element of an array.

pop() It adds one or more elements to the end of an array.

push() It reverses the elements of given array.

reverse() It executes a provided function for each value from left to


right and reduces the arra a single value.
reduce(function,
initial)

It creates a new array carrying sub-array elements


concatenated recursively till specified depth.
37 CST 463 Web Programming
Dept. of CSE ICCSCEM
It executes a provided function for each value from right to
left and reduces the arra a single value.
reduceRight()
It determines if any element of the array passes the test of the
implemented function.
some()
It removes and returns the first element of an array.
shift() It returns a new array containing the copy of the part of the
slice() given array. It returns the element of the given array in a
sort() sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified


array.
toString()
It converts the elements of a specified array into string form,
without affecting original array.
unshift()
It adds one or more elements in the beginning of the given
values()
array. It creates a new iterator object carrying values for each

index in the array.

JavaScript String

The JavaScript string is an object that represents a sequence of


characters. There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)

1) By string literal

The string literal is created using double quotes. The syntax of creating string using string
literal is given below:

1. var stringname="string value";

Let's see the simple example of creating string literal.

1. <script>
2. var str="This is string literal";
3. [Link](str);
4. </script
>
38
CST 463 Web Programming
Dept. of CSE ICCSCEM

2. By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

1. var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Let's see the example of creating string in JavaScript by new keyword.

1. <script>
2. var stringname=new String("hello javascript string");
3. [Link](stringname);
4. </script
>
Output:
hello javascript string

JavaScript String Methods

Let's see the list of JavaScript string methods with examples.

charAt() It provides the char value present at the specified index.


It provides the position of a char value present in the given
string.
charCodeAt()

concat()

indexOf()

It provides the Unicode value of a character present at the


specified index.

It provides a combination of two or more strings.


39 CST 463 Web Programming
Dept. of CSE ICCSCEM

lastIndexOf() It provides the position of a char value present in the given string by searching
character from the last position.
search() It searches a specified regular expression in a given string and returns its position match occurs.

match() It searches a specified regular expression in a given string and returns that reg expression
if a match occurs.
replace() It replaces a given string with the specified replacement.

substr() It is used to fetch the part of the given string on the basis of the specified start position and
length.

substring() It is used to fetch the part of the given string on the basis of the specified index.
slice() It is used to fetch the part of the given string. It allows us to assign positive as negative index.
toLowerCase() It converts the given string into lowercase letter.
toLocaleLowerCase() It converts the given string into lowercase letter on the basis of host?s current locale.
toUpperCase() It converts the given string into uppercase letter.

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of host?s current locale.
toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.


split() It splits a string into substring array, then returns that newly created array. trim() It trims
the white space from the left and right side of the string.

40
CST 463 Web Programming
Dept. of CSE ICCSCEM
JavaScript Number Object

The JavaScript number object enables you to represent a numeric value. It may be integer
or floating-point. JavaScript number object follows IEEE standard to represent the floating
point numbers.

By the help of Number() constructor, you can create number object in JavaScript. For example:

1. var n=new Number(value);

If value can't be converted to number, it returns NaN(Not a Number) that can be checked by
isNaN() method.

You can direct assign a number to a variable also. For example:

1. var x=102;//integer value


2. var y=102.7;//floating point value
3. var z=13e4;//exponent value, output: 130000
4. var n=new Number(16);//integer value by number object

Output:

102 102.7 130000 16

JavaScript Number Constants

Let's see the list of JavaScript number constants with description.

MIN_VALUE returns the largest minimum value.

MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value. NaN represents


"Not a Number" value.

41
CST 463 Web Programming
Dept. of CSE ICCSCEM
JavaScript Number Methods

Let's see the list of JavaScript number methods with their description.

isFinite() It determines whether the given value is a finite number.

It determines whether the given value is an integer.


isInteger()
It converts the given string into a floating point number.
parseFloat()
It converts the given string into an integer number.
parseInt()
It returns the string that represents exponential notation of the
toExponential()
given number. It returns the string that represents a number
toFixed()
with exact digits after a decimal point. It returns the string
toPrecision()
representing a number of specified precision.

toString() It returns the given number in the form of string.

JavaScript Math

The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it doesn't have constructors.

JavaScript Math Methods

Let's see the list of JavaScript Math methods with description.

42
CST 463 Web Programming
Dept. of CSE ICCSCEM
abs() It returns the absolute value of the given number.

acos()
It returns the arccosine of the given number in radians.
asin()
It returns the arcsine of the given number in radians.
atan()
It returns the arc-tangent of the given number in radians.
ceil() It returns a smallest integer value, greater than or equal to the
cos() given number. It returns the cosine of the given number.
exp() It returns the exponential form of the given number.

floor() It returns largest integer value, lower than or equal to the given number. log() It

returns natural logarithm of a number.

pow() It returns value of base to the power of exponent.

trunc() It returns an integer part of the given number.

JavaScript Date Object

The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.

You can use different Date constructors to create date object. It provides methods to get and
set day, month, year, hour, minute and seconds.

Constructor

You can use 4 variant of Date constructor to create date object.

1. Date()
2. Date(milliseconds)

43
CST 463 Web Programming
Dept. of CSE ICCSCEM

3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

JavaScript Date Methods

Let's see the list of JavaScript date methods with their description.

getDate() It returns the integer value between 1 and 31 that represents the day for the specify date
on the basis of local time.

It returns the integer value between 0 and 6 that represents


getDay() the day of the week on basis of local time.

It returns the integer value that represents the year on the


getFullYears() basis of local time.

44
CST 463 Web Programming
Dept. of CSE ICCSCEM
Decision Making and Loops

Decision Making JavaScript


Ifstatement
It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.

1. if(expression){
2. //content to be
evaluated 3. }

Flowchart of JavaScript If statement

45
CST 463 Web Programming
Dept. of CSE ICCSCEM

Let’s see the simple example of if statement in javascript.

1. <script>
2. var
a=20; 3.
if(a>10){
4. [Link]("value of a is greater than
10"); 5. }
6. </script>

Output of the above example

JavaScript If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else
statement is given below.

1. if(expression){
2. //content to be evaluated if condition is
true 3. }

46
CST 463 Web Programming
Dept. of CSE ICCSCEM

4. else{//content to be evaluated if condition is false 6. }

Flowchart of JavaScript If...else statement


Let’s see the example of if-else statement in JavaScript to find out the even or odd number.

1. <script>
2. var a=20;
3. if(a%2==0){
4. [Link]("a is even number"); 5. }
6. else{
7. [Link]("a is odd
number"); 8. }
9. </script>

47
CST 463 Web Programming
Dept. of CSE ICCSCEM
JavaScript If...else if statement

It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.

1. if(expression1){
2. //content to be evaluated if expression1 is
true 3. }
4. else if(expression2){
5. //content to be evaluated if expression2 is
true 6. }
7. else if(expression3){
8. //content to be evaluated if expression3 is
true 9. }
10. else{
11. //content to be evaluated if no expression is true
12. }
Let’s see the simple example of if else if statement in javascript.

1. <script>
2. var
a=20; 3.
if(a==10){
4. [Link]("a is equal to
10"); 5. }

48
CST 463 Web Programming
Dept. of CSE ICCSCEM

6. else if(a==15){
7. [Link]("a is equal to
15"); 8. }
9. else if(a==20){
10. [Link]("a is equal to 20");
11. }
12. else{
13. [Link]("a is not equal to 10, 15 or 20");
14. }
15. </script>

Output of the above example

JavaScript Switch

The JavaScript switch statement is used to execute one code from multiple expressions. It is
just like else if statement that we have learned in previous page. But it is convenient than
if..else..if because it can be used with numbers, characters etc.

The signature of JavaScript switch statement is given below.

1. switch(expression){
2. case value1:
3. code to be executed;
4. break;
5. case value2:
6. code to be executed;
7. br
eak; 8.
......
9.
10. default:
11. code to be executed if above values are not matched;
12. }
49
CST 463 Web Programming
Dept. of CSE ICCSCEM

Let’s see the simple example of switch statement in javascript.

1. <script>
2. var grade='B';
3. var result;
4. switch(grade){
5. case 'A':
6. result="A Grade";
7. break;
8. case 'B':
9. result="B Grade";
10. break;
11. case 'C':
12. result="C Grade";
13. break;
14. default:
15. result="No Grade";
16. }
17. [Link](result);
18. </script>

Output of the above example

JavaScript Loops

The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

1. for loop
2. while loop

50
CST 463 Web Programming
Dept. of CSE ICCSCEM

3. do-while loop

1) JavaScript For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.

1. for (initialization; condition;


increment) 2. {
3. code to be
executed 4. }

Let’s see the simple example of for loop in javascript.

1. <script>
2. for (i=1; i<=5;
i++) 3. {
4. [Link](i +
"<br/>") 5. }
6. </script>
Output:

2) JavaScript while loop

The JavaScript while loop iterates the elements for the infinite number of times. It should be
used if number of iteration is not known. The syntax of while loop is given below.

1. while (condition)

51
CST 463 Web Programming
Dept. of CSE ICCSCEM

2. {
3. code to be
executed 4. }

Let’s see the simple example of while loop in javascript.

1. <script>
2. var i=11;
3. while
(i<=15) 4. {
5. [Link](i +
"<br/>"); 6. i++;
7. }
8. </script>

Output:
3) JavaScript do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like while
loop. But, code is executed at least once whether condition is true or false. The syntax of do
while loop is given below.

1. do{
2. code to be executed
3. }while (condition);

52
CST 463 Web Programming
Dept. of CSE ICCSCEM

Let’s see the simple example of do while loop in javascript.

1. <script>
2. var i=21;
3. do{
4. [Link](i +
"<br/>"); 5. i++;
6. }while (i<=25);
7. </script>

Output:
Browser Object Model

The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:

1. [Link]("hello javatpoint");
is same as:
1. alert("hello javatpoint");

You can use a lot of properties (other objects) defined underneath the window object like
document, history, screen, navigator, location, innerHeight, innerWidth,

53
CST 463 Web Programming
Dept. of CSE ICCSCEM
Document Object Model

The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is the root
element that represents the html document. It has properties and methods. By the help of
document object, we can add dynamic content to our web page.

54
CST 463 Web Programming

You might also like