You are on page 1of 22

Chapter 4: Client Side Scripting (JavaScript)

4.1. Introduction to JavaScript

What is JavaScript?

 A script is a small piece of program that can add interactivity to your website. For
example, a script could generate a pop-up alert box message, or provide a dropdown
menu. This script could be written using JavaScript


.
 JavaScript (js) is a light-weight object-oriented programming language which is used by
several websites for scripting the webpages.
 JavaScript can change HTML Content.
 One of many JavaScript HTML methods is getElementById().
 The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":
Example
 document.getElementById("demo").innerHTML = "Hello JavaScript";
 JavaScript accepts both double and single quotes:
Example
 document.getElementById('demo').innerHTML = 'Hello JavaScript';
 JavaScript Can Change HTML Styles (CSS)
 Changing the style of an HTML element is a variant of changing an HTML attribute:
Example
 document.getElementById("demo").style.fontSize = "35px";
 JavaScript Can Hide HTML Elements
 Hiding HTML elements can be done by changing the display style:
Example
 document.getElementById("demo").style.display = "none";
 JavaScript Can Show HTML Elements
 Showing hidden HTML elements can also be done by changing the display style:
Example
document.getElementById("demo").style.display = "block";

4.2. JavaScript Basic


4.2.1 JavaScript Syntax

The <script> Tag

 In HTML, JavaScript code is inserted between <script> and </script> tags.

Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

 Old JavaScript examples may use a type attribute: <script type="text/javascript">.


The type attribute is not required. JavaScript is the default scripting language in HTML.

JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are constructed:

//Howto create variables:


var x;
let y;
// How to use variables:
x= 5;
y= 6;
let z=x+y;
JavaScript Keywords

 JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.

Here is a list of some of the keywords you will learn about in this tutorial:

Keyword Description

var Declares a variable

let Declares a block variable

const Declares a block constant

if Marks a block of statements to be executed on a condition


switch Marks a block of statements to be executed in different cases

for Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of statements

 JavaScript keywords are reserved words. Reserved words cannot be used as names for
variables.

4.2.2.. Attaching JavaScript to HTML (External, Embedded, Inline)


There are three way to write JavaScript into html. These are: inline, Internal and external
External JavaScript file
 We can create external JavaScript file and embed it in many html page.
 It provides code re usability because single JavaScript file can be used in several html
pages.
 An external JavaScript file must be saved by .js extension. It is recommended to embed
all JavaScript files into a single file. It increases the speed of the webpage.
4.3 JavaScript Comments

 JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
 JavaScript comments can also be used to prevent execution, when testing alternative
code.

Single Line Comments


 Single line comments start with //.
 Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).
 This example uses a single-line comment before each code line:
Example
// Change heading:
document.getElementById("myH").innerHTML = "My First Page";

// Change paragraph:
document.getElementById("myP").innerHTML = "My first paragraph.";

This example uses a single line comment at the end of each line to explain the code:
Example
let x = 5; // Declare x, give it the value of 5
let y = x + 2; // Declare y, give it the value of x + 2

Multi-line Comments
 Multi-line comments start with /* and end with */.
 Any text between /* and */ will be ignored by JavaScript.
 This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";

4.4. Basic JavaScript Input Output


JavaScript Output
JavaScript Display Possibilities

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML
 To access an HTML element, JavaScript can use
the document.getElementById(id) method.
 The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example
<!DOCTYPE html>
<html>
<body>

<h1>MyFirstWebPage</h1>
<p>MyFirstParagraph</p>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>

Changing the innerHTML property of an HTML element is a common way to display data in
HTML.

Using document.write()

For testing purposes, it is convenient to use document.write():

Example
<!DOCTYPE html>
<html>
<body>
<h1>MyFirstWebPage</h1>
<p>Myfirstparagraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>

Using document.write() after an HTML document is loaded, will delete all existing HTML:

Example
<!DOCTYPE html>
<html>
<body>
<h1>MyFirstWebPage</h1>
<p>Myfirstparagraph.</p>
<button type="button" onclick="document.write(5+6)">Tryit</button>
</body>
</html>

 The document.write() method should only be used for testing.

Using window.alert()

You can use an alert box to display data:


Example
<!DOCTYPE html>
<html>
<body>
<h1>MyFirstWebPage</h1>
<p>Myfirstparagraph.</p>
<script>
window.alert(5 + 6);
</script>
</body>
</html>

 You can skip the window keyword.


 In JavaScript, the window object is the global scope object, that means that variables,
properties, and methods by default belong to the window object. This also means that
specifying the window keyword is optional:
Example
<!DOCTYPE html>
<html>
<body>
<h1>MyFirstWebPage</h1>
<p>Myfirstparagraph.</p>
<script>
alert(5 + 6);
</script>

</body>
</html>

Using console.log()

 For debugging purposes, you can call the console.log() method in the browser to display
data.

Example
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>
</body>
</html>

JavaScript Print
 JavaScript does not have any print object or print methods.
 You cannot access output devices from JavaScript.
 The only exception is that you can call the window.print() method in the browser to print
the content of the current window.
Example
<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Printthispage</button>

</body>
</html>

JavaScript Statements
Example
let x,y,z; / Statement 1
x= 5; // Statement 2
y= 6; // Statement 3
z = x + y; // Statement 4

4.5JavaScript Data Types and Variables


4.5.1 JavaScript Data types

JavaScript Variables

There are 3 ways to declare a JavaScript variable:

 Using var
 Using let
 Using const

This chapter uses var.

Variables
 Variables are containers for storing data (values).
 In this example, x, y, and z, are variables, declared with the var keyword:
Example
var x= 5;
var y= 6;
var z = x + y;

From the example above, you can expect:

 x stores the value 5


 y stores the value 6
 z stores the value 11

JavaScript Identifiers
 All JavaScript variables must be identified with unique names.
 These unique names are called identifiers.
 Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

 JavaScript identifiers are case-sensitive.

JavaScript Statements
 JavaScript statements are composed of:
 Values, Operators, Expressions, Keywords, and Comments.
 This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
document.getElementById("demo").innerHTML = "Hello Dolly.";

 Most JavaScript programs contain many JavaScript statements.


 The statements are executed, one by one, in the same order as they are written.
 JavaScript programs (and JavaScript statements) are often called JavaScript code.
 Semicolons ;
 Semicolons separate JavaScript statements.
 Add a semicolon at the end of each executable statement:
Examples
let a,b,c; // Declare 3 variables
a= 5; // Assign the value 5 to a
b= 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c

 When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;
JavaScript Dollar Sign $
Remember that JavaScript identifiers (names) must begin with:
 A letter (A-Z or a-z)
 A dollar sign ($)
 Or an underscore (_)

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

Example
var $$$= "HelloWorld";
var $= 2;
var $myMoney= 5;

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

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

Example
var _lastName= "Johnson";
var _x= 2;
var _100= 5;

 Using the underscore is not very common in JavaScript, but a convention among
professional programmers is to use it as an alias for "private (hidden)" variables.

4.5.2 Variable declaration in JavaScript


JavaScript Operators
Example

Assign values to variables and add them together:

let x = 5; // assign the value 5 to x


let y = 2; // assign the value 2 to y
let z = x + y; // assign the value 7 to z (5 + 2)

The assignment operator (=) assigns a value to a variable.

Assignment
let x = 10;

The addition operator (+) adds numbers:

Adding
let x = 5;
let y = 2;
let z = x + y;

The multiplication operator (*) multiplies numbers.

Multiplying
let x = 5;
let y = 2;
let z = x * y;

4.6Arithmetic and Logical Operators in JavaScript

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation (ES2016)
/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

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

The addition assignment operator (+=) adds a value to a variable.

Assignment
let x = 10;

x += 5;

JavaScript String Operators

 The + operator can also be used to add (concatenate) strings.

Example
let text1= "John";
let text2= "Doe";
let text3 = text1 + " " + text2;

The result of text3 will be:

John Doe
 The += assignment operator can also be used to add (concatenate) strings:

Example
let text1= "What a very ";
text1 += "nice day";

The result of text1 will be:

What a very nice day

 When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers will return the sum, but adding a number and a string will return a string:

Example
let x= 5 + 5;
let y= "5" + 5;
let z= "Hello" + 5;

The result of x, y, and z will be:

10
55
Hello5

If you add a number and a string, the result will be a string!

JavaScript Comparison Operators

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to


<= less than or equal to

? ternary operator

JavaScript Logical Operators

Operator Description

&& logical and

|| logical or

! logical not

JavaScript Bitwise Operators

 Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to a JavaScript number.

Operator Description Example Same as Result

& AND 5&1 0101 & 0001 0001

| OR 5|1 0101 | 0001 0101

~ NOT ~5 ~0101 1010

^ XOR 5^1 0101 ^ 0001 0100

<< Zero fill left shift 5 << 1 0101 << 1 1010

>> Signed right shift 5 >> 1 0101 >> 1 0010

>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010

4.7 Control Structures (Conditional and Looping Statements)


JavaScript If-else

The JavaScript if-else statement is used to execute the code whether condition is true or false.
There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement

It evaluates the content only if expression is true.

if(expression){
//content to be evaluated
}
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

Output of the above example


value of a is greater than 10

JavaScript If...else Statement


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

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

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

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
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.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
4.9JavaScript Functions
A function allows you to define a block of code, give it a name and the execute it as many times
as you want.

Example:

<!DOCTYPE html>
<html>

<head>
<title>Event Handlers Example</title>

<script type = "text/JavaScript">


function EventHandler() {
alert("I'm event handler!!");
}
</script>
</head>

<body>
<p onmouseover = "EventHandler();">Bring your mouse here to see an alert</p>
</body>

</html>
4.10. JavaScript DOM (Document object Model)

What is the DOM?

The HTML DOM defines a standard way for accessing and manipulating HTML
documents. It presents an HTML document as a tree-structure.

The HTML DOM

 All HTML elements can be accessed through the HTML DOM.


 This example changes the value of an HTML element with id="demo":

Example
<h1 id="demo">This is a Heading</h1>

<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

4.10.1. Accessing HTML elements in JavaScript

When you want to access HTML elements with JavaScript, you have to find the elements first.

There are a couple of ways to do this:

 Finding HTML elements by id


 Finding HTML elements by tag name
 Finding HTML elements by class name
 Finding HTML elements by CSS selectors
 Finding HTML elements by HTML object collections

Finding HTML Element by Id

 The easiest way to find an HTML element in the DOM, is by using the element id.
 This example finds the element with id="intro":
Example
 var myElement = document.getElementById("intro");
 If the element is found, the method will return the element as an object (in myElement).
 If the element is not found, myElement will contain null.
Finding HTML Elements by Tag Name
This example finds all <p> elements:
Example
var x = document.getElementsByTagName("p");
This example finds the element with id="main", and then finds all <p> elements
inside "main":
Example
 var x = document.getElementById("main");
var y = x.getElementsByTagName("p");
Finding HTML Elements by Class Name
 If you want to find all HTML elements with the same class name, use
getElementsByClassName().
 This example returns a list of all elements with class="intro".
Example
 var x = document.getElementsByClassName("intro");
 Finding elements by class name does not work in Internet Explorer 8 and
earlier versions.
Finding HTML Elements by CSS Selectors
 If you want to find all HTML elements that matches a specified CSS selector
(id, class names, types, attributes, values of attributes, etc), use the
querySelectorAll() method.
 This example returns a list of all <p> elements with class="intro".
Example
 var x = document.querySelectorAll("p.intro");
 The querySelectorAll() method does not work in Internet Explorer 8 and earlier
versions.
Note: The document object represents an html document. It forms DOM (Document
Object Model).
4.11. Form Processing using JavaScript

4.12. 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:
window.alert("hello javatpoint");
is same as
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,
Identifying BOM Objects

In order to program BOM objects, they must be identified to the scripts that
manipulate their properties and methods.
Reference Object
window The main browser window
window.navigator Information about the browser itself
window.screen The user's screen
window.history URLs visited by a user
window.location The current URL
The document appearing in the main browser
window.document (document)
window
An HTML element appearing in a document and
identified by its assigned id value.
document.getElementById("id")

4.12.1. JavaScript Window

The Window Object

 The window object is supported by all browsers. It represents the browser's


window.
 All global JavaScript objects, functions, and variables automatically become members of
the window object.
 Global variables are properties of the window object.
 Global functions are methods of the window object.
 Even the document object (of the HTML DOM) is a property of the window object:

window.document.getElementById("header");

is the same as:


document.getElementById("header");
Window Size
Two properties can be used to determine the size of the browser window.
Both properties return the sizes in pixels:
 window.innerHeight - the inner height of the browser window (in pixels)
 window.innerWidth - the inner width of the browser window (in pixels)
The browser window (the browser viewport) is NOT including toolbars and
scrollbars.
Example
let w = window.innerWidth;
let h = window.innerHeight;
Other Window Methods
Some other methods:
 window.open() - open a new window
 window.close() - close the current window
 window.moveTo() - move the current window
 window.resizeTo() - resize the current window
4.12.2, JavaScript Location

The window.location object can be written without the window prefix.


Some examples:
 window.location.href returns the href (URL) of the current page
 window.location.hostname returns the domain name of the web host
 window.location.pathname returns the path and filename of the current page
 window.location.protocol returns the web protocol used (http: or https:)
 window.location.assign() loads a new document
Window Location Href
The window.location.href property returns the URL of the current page.
Example
 Display the href (URL) of the current page:
 document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
Result is:
Page location is file:///C:/Users/hp/Desktop/htmll/BOM/JavaScript%20Window%20Location.html
Window Location Hostname
 The window.location.hostname property returns the name of the internet host (of the
current page).
Example

 Display the name of the host:


 document.getElementById("demo").innerHTML =
"Page hostname is " + window.location.hostname;

Result is:
Page hostname is

Window Location Protocol

The window.location.protocol property returns the web protocol of the page.


Example

Display the web protocol:


 document.getElementById("demo").innerHTML =
"Page protocol is " + window.location.protocol;

Result is:
Page protocol is file:

Window Location Port

 The window.location.port property returns the number of the internet host port (of
the current page).
Example
Display the name of the host:

 document.getElementById("demo").innerHTML =
"Port number is " + window.location.port;

Result is:

Port number is

Most browsers will not display default port numbers (80 for http and 443 for https)

Window Location Assign

 The window.location.assign() method loads a new document.


Example

Load a new document:


<html>
<head>
<script>
function newDoc() {
window.location.assign("https://www.w3schools.com")
}
</script>
</head>
<body>

<input type="button" value="Load new document" onclick="newDoc()">


</body>
</html>
4.12.3.. JavaScript Cookies

What are Cookies?


 Cookies are data, stored in small text files, on your computer.
 When a web server has sent a web page to a browser, the connection is shut
down, and the server forgets everything about the user.

Cookies were invented to solve the problem "how to remember information about the
user":

 When a user visits a web page, his/her name can be stored in a cookie.
 Next time the user visits the page, the cookie "remembers" his/her name.

Cookies are saved in name-value pairs like:


username = John Doe
 When a browser requests a web page from a server, cookies belonging to the
page are added to the request. This way the server gets the necessary data to
"remember" information about users.
 None of the examples below will work if your browser has local cookies
support turned off.
Create a Cookie with JavaScript
 JavaScript can create, read, and delete cookies with the document.cookie property.
 With JavaScript, a cookie can be created like this:
document.cookie = "username=John Doe";
 You can also add an expiry date (in UTC time). By default, the cookie is
deleted when the browser is closed:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
 With a path parameter, you can tell the browser what path the cookie belongs to. By
default, the cookie belongs to the current page.
 document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC;
path=/";
Read a Cookie with JavaScript
 With JavaScript, cookies can be read like this:
 let x = document.cookie;
 document.cookie will return all cookies in one string much like: cookie1=value;
cookie2=value; cookie3=value;
Change a Cookie with JavaScript
 With JavaScript, you can change a cookie the same way as you create it:
 document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013
12:00:00 UTC; path=/";
The old cookie is overwritten.
Delete a Cookie with JavaScript
 Deleting a cookie is very simple.
 You don't have to specify a cookie value when you delete a cookie.
 Just set the expires parameter to a past date:
 document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC;
path=/;";
 You should define the cookie path to ensure that you delete the right cookie.
 Some browsers will not let you delete a cookie if you don't specify the path .

You might also like