3 Javascript PDF
3 Javascript PDF
3 Javascript PDF
Audience
This tutorial has been designed to meet the requirements of all
those readers who are keen to learn the basics of JAVASCRIPT.
Prerequisites
This book assumes you have no prior knowledge on Programming
knowledge and assume you are at a beginner level.
All the content and graphics published in this e-book are the
property of PHPBootcamp.com. The user of this e-book is prohibited
to reuse, retain, copy, distribute or republish any contents or a part
of contents of this e-book in any manner without written consent of
the publisher.
Support
You can reach me for technical discussions and other support
related queries from here.
Free Courses
Learn JAVASCRIPT in 1
Hour
Table of Contents
1. JavaScript Basics
1 JavaScript Basics
Invention of JavaScript
In 1995, Brandon Eich Wrote Java Script and main purpose of it was
to change the DOM which was created by the HTML.
History of JavaScript
Future of JavaScript
SYNTAX:
<head>
<script>
</script>
</head>
If you have two <script> tag one after the other then code inside the
<script> executes one after the other.
If you put the <script> tag at the end of the <body> tag then the
script is executed at the last after the page is loaded.
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</script>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph Text</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Put the <script> tag with alert at the end of the page in
the <body> section.
Live Preview
Exercise 2
Exercise 2: Put the script tag with alert with tags in the <body>
section and see if that works.
Also, Press “OK” button and then Press F5 to see if the alert box
comes again.
Live Preview
Usage of Comments
You can use the special notation to comment the code inside the
JavaScript.
HTML comments and JavasScript comments are not same. Don’t get
confused with the comments in JavaScript vs comments in HTML.
SYNTAX:
<head>
<script>
</sript>
</head>
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta name="description" content="Page Description">
<title>How to Write Comments in JavaScript</title>
<script>
/*
This is a multi-line comment in JS.
This is different than the HTML comments.
Anything inside this block will be ignored.
</script>
<!-- This is HTML Comments -->
</head>
<body>
<h1>Heading</h1>
<p>Paragraph Text</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Make the multi-line comments that looks like single line.
Live Preview
Exercise 2
Exercise 2:
Observe how the HTML comments can comment all the <script>
tags
2. Write Multi Line Comments inside the Multi Line comments and
see it shows an error on the page.
Live Preview
JavaScript (JS) can be written in another file and included inside the
HTML page.
Benefit of using this external JS is that you have one JS file that is
included in all the website pages.
By just changing at one place in the JS it will impact the overall site
design look and feel.
This is one of the best practice to separate the design with the html
tags and store them in a external file and include it in all the HTML
pages.
SYNTAX:
<head>
<!– Make sure javascriptcode.js file exists in the ‘javascript’ folder –>
<script type=’text/javascript‘
src=”javascript/javascriptcode.js”></script>
</head>
<script> tag is used to link the resource to the HTML page. The
attribute of script tag will let the browser knows what type of
resource it is.
src attribute is similar to <img> tag src to map the location of the file
in the server with the path and filename. You can even mention the
foldername/file name to refer the file path.
Sample Example
index.html
javascript/javascriptcode.js
type attribute tells the type of the content in the file. In this case, it is
text/javascript
FileName: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>External JavaScript</title>
<script type='text/javascript'
src="javascript/javascriptcode.js"></script>
</head>
<body>
<h1>External JavaScript!</h1>
<p>Paragraph Text</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
FileName: javascriptcode.js
alert('I am called from javasriptcode.js file!');
Live Preview
Exercise 1
Exercise 1: Create js1.js and js2.js and link them in the HTML page.
Do not create folder and place the js files along with the HTML file.
Filename: js1.js
Filename: js2.js
Live Preview
Exercise 2
Exercise 2: Place one <script> tag inside the <head> tag and put
another <script> tag at the end of <body>.
Live Preview
Inline JavaScript is defined inside the HTML tag itself like an attribute.
Inline JS overrides all the styles defined in internal JS and External JS.
SYNTAX:
onclick is a event for <a> tag and it is called when user clicks on the
link.
Calling this alert is handled by the browser itself. When user clicks on
the link, browser will raise the click event on this tag and because we
ask to raise an alert when this event is raised. This method is called.
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Inline JavaScript</title>
</head>
<body>
<a href="#" onclick="alert('Welcome to JavaScript!');">Click Me</a>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Add an Image and on clicking the image show an alert message.
Live Preview
Exercise 2
Find the area when clicked – alert is raised and find the area where
alerts are not raised on the body.
Live Preview
But the best way is to organize your code into one file so that it is
easy to fix issues at one place for your entire site.
For this hello world sample, we will use the inline javascript. Once we
know how to write functions and call them from on click even then
we improve this program.
Instead of alert we will use confirm method that shows ok and cancel
button.
confirm(‘Enjoying JavaScript!’);
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Sample JavaScript Program!</title>
</head>
<body>
<h1>Sample JavaScript Program</h1>
<p>Paragraph Text</p>
<a href="#" onclick="alert('Hello World!');">Hello Message!</a>
<br>
<a href="#" onclick="confirm('Enjoying JavaScript!');">Do you Like?</a>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Show list of items 1, 2 and 3. When user clicks any links
show what they have clicked.
Live Preview
Exercise 2
Live Preview
These are the terms you need to know if you are a JavaScript
Programmer.
Example : +, -, ++
y = sum(1, 2);
alert(“value of y” + y);
Because JavaScript runs in the browser the only way to debug the
JavaScript program is from the browser tools
Chrome and Firefox has plenty of debugging tools that can help to
find the issue and fix it. You can pause the execution of javascript
program and debug it steps by step.
You need to learn this method to find the issues in JavaScript and Fix
it.
Inspect Window:
Load any HTML program with JavaScript in Chrome and press CTRL +
SHIFT + I.
Console Tab:
Console tab is the output tab where you can write the logs of your
program and view it.
Even browser will it is own log here if there is any issue in the HTML
program.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>External JavaScript</title>
<script type='text/javascript' src="js1.js"></script>
</head>
<body>
<h1>External JavaScript!</h1>
<p>Paragraph Text</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Live Preview
2.1 Identifiers
Usage of Identifiers
There are some rules that you need follow to define the Identifiers.
• strFirstName
• $var
• index_1
• crashReport
InValid Identifiers:
• 1PhoneNumber
• false
• long
• package
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Identifiers JavaScript</title>
<script>
</script>
</head>
<body>
<a href="#" onclick="ALERT('Welcome to JavaScript!');">Click Me</a>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Live Preview
2.2 Variables
Usage of Variables
Variables are used to store information which are used inside the
program.
SYNTAX:
//Declaring a Variable
var variableName;
//Multiple Variable
var name1, name2, name3;
nam1 = “firstName”, name2 = “middleName”, name3
=”lastName”;
<script type=”text/javascript”>
document.write(“Your Message” + message + “<br>”);
</script>
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Variables</title>
<script>
//Declaring a Variable
var message;
var counter = 0;
alert("2) Counter Before: " + counter);
message = "2) Counter Before: " + counter;
console.log(message);
counter = 100;
alert("3) Counter After: " + counter);
message = "3) Counter After: " + counter;
console.log(message);
</script>
</head>
<body>
<h1>Variables</h1>
<script type="text/javascript">
document.write("Your last Message: " + message);
</script>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Count the number of times the user clicked the link and
show it for every click on the link.
Define the counter variable in the head -> script section and track the
number of clicks and show it in the console.log.
Snippet:
Live Preview
Exercise 2
Exercise 2: Accept two names from User and Display them on the
HTML page.
Live Preview
2.3 Primitives
Primitive data types means the basics data types that can be used in
JavaScript programs.
Numeric Data:
var count = 1;
String Data:
Boolean Data:
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Primitive</title>
<script>
</script>
</head>
<body>
<h1>Check the Console Log</h1>
</body>
</html>
Live Preview
Exercise 1
Tip:
Live Preview
Exercise 2
Tip:
var userAnswer = confirm(“Do you like grapes?”);
Live Preview
2.4 Keywords
Keywords
These are the list of the keywords that you should not use to define
variables.
Reserved Words
These are the list of the reserved words that you should not use to
define variables, functions, objects or properties.
3 Expressions in JavaScript
1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions
message = “something”; is a assignment expression that assign value to the message variable.
• +=
• -=
• *=
counter += 1;
counter = counter + 1;
counter -= 1;
counter = counter – 1;
counter *= 1;
counter = counter * 1;
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Assignment Expressions</title>
<script>
var counter = 10;
</script>
</head>
<body>
<h1>Assignment Expressions</h1>
<a href="#" onclick="counter+=1;console.log(counter);">Increase
Counter</a>
<a href="#" onclick="counter-=1;console.log(counter);">Decrease
Counter</a>
<a href="#" onclick="counter*=2;console.log(counter);">Multiple
Counter</a>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Ask user to enter a number and display the square of this
number.
Live Preview
Exercise 2
Live Preview
1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions
Comparison Operations:
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Comparison Expressions</title>
<script>
var counter = 10 <= 10;
</script>
</head>
<body>
<h1>Comparison Expressions</h1>
<script type="text/javascript">
document.write("Compared: " + counter + "<br>");
document.write("Result Value: " + resultValue);
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Exercise 2: Find out a Even number and Odd Number from the
number entered by the User.
Tips:
var resultValue = (counter%2) ? “ODD NUMBER”: “EVEN NUMBER”;
Live Preview
1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions
Arithmetic Operations:
• + – Addition
• – Subtraction
• * – Multiple
• / – Division
• % – Modulus
• ++ – Increment
• — Decrement
Order of Precedence
• ++
• —
• */%
• +–
Increment Example:
counter = 10;
counter++; // This means counter = counter + 1;
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Arithmetic Expressions</title>
<script>
var counter = 10;
console.log(counter);
</head>
<body>
<h1>Arithmetic Expressions</h1>
<a href="#" onclick="counter++;console.log(counter);">Increase
Counter</a>
<a href="#" onclick="counter--;console.log(counter);">Decrease
Counter</a>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Exercise 2: Ask length and breadth from the user and calculate the
area of a rectangle and display on the page.
Tips:
var resultValue = length * breadth;
Live Preview
1. Assignment Expressions
2. Comparison Expressions
3. Arithmetic Expressions
4. Logical Expressions
&& is the logical operator which checks left side and right side value
and decides if the condition is true or false.
(5 > 3) – true
(8 < 5) – false
true && false = false
Logical Operations:
• && – AND
• || – OR
• ! – NOT
Order of Precedence
• NOT
• AND
• OR
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Arithmetic Expressions</title>
<script>
var input1 = prompt("Enter First Value: ");
var input2 = prompt("Enter Second Value: ");
</script>
</head>
<body>
<h1>Arithmetic Expressions</h1>
<script type="text/javascript">
document.write(input1 + " <= " + input2 + " is "+ result);
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Live Preview
There two string operators that can be used to join the string:
1. +
2. +=
Examples:
String Methods:
• indexOf(search, position)
• substr(start, length)
• substr(start, stop)
• toLowerCase()
• toUpperCase()
alert( name.toLowerCase() );
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>String Expressions</title>
<script>
var input1 = prompt("Enter Your First Name: ");
var input2 = prompt("Enter Your Last Name: ");
</script>
</head>
<body>
<h1>String Expressions</h1>
<script type="text/javascript">
document.write(userName);
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Exercise 2: Define the String variable like and observe the output.
Live Preview
3.6 Quotes
Usage of Quotes in Strings
Escape Sequence:
Sample Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>String Expressions</title>
<script>
var input1 = prompt("Enter Your First Name: ");
var input2 = prompt("Enter Your Last Name: ");
</script>
</head>
<body>
<h1>String Expressions</h1>
<script type="text/javascript">
document.write(userName);
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Live Preview
3.7 Boolean
Usage of Boolean
Example:
var isTrue= “Henry” == “H3nry”;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Boolean Expressions</title>
<script>
</script>
</head>
<body>
<h1>Boolean Expression</h1>
<script type="text/javascript">
document.write(message);
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Exercise 2: Ask user to guess a word that starts with A and then
match it with the word that you guessed it.
Live Preview
3.8 Arrays
Usage of Arrays
Arrays are special type of Objects that holds one or more items
called as elements.
Define an Array
ARRAY LITERAL:
ARRAY CONSTRUCTOR:
arrayName[index]
newArray[0] = ‘white’;
newArray[1] = ‘red’;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Boolean Expressions</title>
<script>
</head>
<body>
<h1>Arrays</h1>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Live Preview
By default, dt will have user system date and it can be displayed with
its methods.
Date Methods
Examples:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Date and Time</title>
<script>
console.log(today.toDateString());
console.log(today.getFullYear());
console.log(today.getDate());
console.log(today.getMonth());
</script>
</head>
<body>
<h1>Date and Time</h1>
<script type="text/javascript">
document.write(today.toDateString()+"<br>");
document.write(today.getFullYear()+"<br>");
document.write(today.getDate()+"<br>");
document.write(today.getMonth()+"<br>");
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Live Preview
4.Statements
4 Statements
4.1 if Statements
Usage of if Statements
It can choose some action when the condition is true and also take
some action when it false.
You can nest multiple conditions together and decide to choose one
action based on multiple conditions.
Syntax:
if ( condition1 ){
// Statements
// Statements
} else {
// Statements
Example 1:
}else{
alert(“Try Again!”);
Example 2:
}else{
alert(“Try Again!”);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>if Statements</title>
<script>
</script>
</head>
<body>
<h1>if Statements</h1>
<script type="text/javascript">
document.write( result );
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Exercise 2: Ask user to enter the age and decides if he is kid, man
(age > 21) or senior citizen (age > 55).
Live Preview
Syntax:
switch( variable ){
case value:
//Statement
break;
case value:
//Statement
break;
default:
//Statement
break;
Example 1:
switch ( dayOfWeek ){
case ‘Mon’:
alert(“Welcome Monday”);
break;
case ‘Tuesday’:
alert(“Welcome Tuesday”);
break;
default:
alert(“Try Again!”);
break;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Switch Statements</title>
<script>
switch(dayOfWeek){
case 'monday':
result = "First Day of Week";
break;
case 'tuesday':
result = "Second Days of Week";
break;
case 'wednesday':
result = "Mid Week";
break;
case 'thursday':
result = "Preparing for Weekend";
break;
case 'friday':
result = "It's Friday!";
break;
case 'saturday':
result = "Enjoying Day!";
break;
case 'sunday':
result = "Resting Day!";
break;
default:
result = "Cannot find that Value!";
}
</script>
</head>
<body>
<h1>Switch Statements</h1>
<script type="text/javascript">
document.write( result );
</script>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
Exercise 2: Ask user to enter the age and decides if he is kid, man
(age > 21) or senior citizen (age > 55). Use the Switch Statement.
Tips:
switch(true){
//Statements
break
Live Preview
While statement are used to loop a block code and run it until a
condition is met.
Syntax:
while( condition ) {
//Statements
Example 1:
var counter = 0;
counter++;
Syntax:
do{
//Statement
}while ( condition );
Example 1:
var counter = 0;
do{
counter++;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>While Statements</title>
<script>
var counter = 0;
while( counter <= 10){
console.log("While Counter: " + counter++);
}
counter = 0;
do{
console.log("Do Counter: " + counter++);
}while( counter <= 10);
</script>
</head>
<body>
<h1>While Statements</h1>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Accept two number from user and print all the numbers
between them. Print only maximum of 10 numbers.
break; – is a keyword that can be used in the loop to break from the
loop.
Tip:
Live Preview
Exercise 2
Exercise 2: Accept two number from user and print EVEN numbers
only between them. Print only maximum of 10 numbers.
Live Preview
for Loop are used to loop a block code and run it until a condition is
met.
Syntax:
//Statements
Example 1:
alert(counter);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>For Statements</title>
<script>
</head>
<body>
<h1>For Statements</h1>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Accept two number from user and print all the numbers
between them. Print only maximum of 10 numbers.
break; – is a keyword that can be used in the loop to break from the
loop.
Live Preview
Exercise 2
Exercise 2: Accept two number from user and print EVEN numbers
only between them. Print only maximum of 10 numbers.
Live Preview
5.1 Functions
Usage of Functions
You can pass parameters to functions and it can return a value from
the function using “return” keyword.
function nameOfFunction(Parameters){
return someValue;
Example 1:
return someValue;
Example 1:
}() );
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Functions</title>
<script>
</script>
</head>
<body>
<h1>Functions</h1>
<a href="#" onclick="alert( sum(2,5) );">Add 2 + 5</a>
<br>
<a href="#" onclick="alert( size(10,20) );">Area of 10 * 20</a>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Accept two number from users and add those two
numbers using functions.
Live Preview
Exercise 2
Exercise 2: Accept two number from user and print EVEN numbers
only between them. Print only maximum of 10 numbers.
Live Preview
5.2 Objects
Usage of Objects
Object Literal:
var hotel = {
numberOfRooms: 10,
bookedRooms: 5,
checkAvailability(): function(){
};
or
Creating an Object:
hotel.numberOfRooms = 10;
hotel.bookedRooms = 5;
hotel.checkAvailability = function(){
this.numberOfRooms = totalRooms;
this.bookedRooms = roomLeft;
this.checkAvailability = function(){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Objects</title>
<script>
function Area(a, b)
{
this.input1 = a;
this.input2 = b;
this.getArea = function(){
return this.input1 * this.input2;
}
}
input1 = parseInt(input1);
input2 = parseInt(input2);
</script>
</head>
<body>
<h1>Objects</h1>
<script type="text/javascript">
document.write("Area - " + result);
</script>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Accept two number from users and add those two
numbers using Objects.
Live Preview
Exercise 2
Exercise 2: Accept two number from user and print EVEN numbers
only between them. Print only maximum of 10 numbers.
Live Preview
5.3 Events
Usage of Events
• onClick
• ondblClick
• onmouseover
• onmouseup
• onmouseout
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Events JavaScript</title>
</head>
<body>
<a href="#" onclick="alert('Welcome to JavaScript!');">Click Me</a>
<br>
<a href="#" onmouseover="alert('Welcome to JavaScript!');">MouseOver
me</a>
</body>
</html>
Live Preview
Exercise 1
Live Preview
Exercise 2
6 Testing
6.1 Debugging
Step 1: Write JavaScript Code with Errors
Live Preview 1
1. Add Sum() method in the Javascript file and do not create that
function. This will cause the program to fail.
Live Preview 2
Download the Source code and open the HTML file using the chrome
browser and test it.
1. CTRL + SHIFT + I
2. F12
3. Top-Right Menu -> More Tools -> Developer Tools
Step 4: Debug
1. Once you open the console window it show the errors with red
color. Clicking on the link will take you to the javascript error
code.
2. Click on Source Tab and open the file. It will show any errors in
the file with red cross marks.
These are the most common JavaScript errors that you might make
while writing the JavaScript.
Example:
Example:
//Missing Parenthesis
if ( x > y) && (y > 100) {
Example:
Funtion add(){
}
Example:
//Keywords as Variable
var name = “hello”;
Example:
function add(){
}
Example:
The process of making sure the code will not break and if it does it
know the reason for it and make a clean exit.
SYNTAX:
try{
//Statements
}catch(errorName) {
//Statments
Example:
try{
}catch(error){
alert(error);
}finally{
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Try Catch JavaScript</title>
<script>
try{
}catch(error){
//Catch the error
alert(error);
}finally{
//This will execute every time with or without error
alert("Have a good Day!");
}
</script>
</head>
<body>
<h1>Heading</h1>
<p>Paragraph Text</p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Accept one number from user and raise error if the
number is not integer.
if( isNaN(input1) ){
Live Preview
Exercise 2
Live Preview
What is DOM?
DOM is created by the browser for the HTML page so that it can
easily navigate and make changes to the elements.
You can read any element from the DOM using JavaScript functions:
1. getElementById(idName)
2. getElementsByTagName(tagName)
3. getElementByName(name)
4. getElementByClassName(className)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Inline JavaScript</title>
<script>
function show(){
var txtValue = document.getElementById('txtName').value;
alert( txtValue );
}
</script>
</head>
<body>
<h1>Access the DOM Elements</h1>
<form>
</html>
Live Preview
Exercise 1
Tips:
var txtValue = document.getElementsByName(‘txtName’)[0].value;
Live Preview
Exercise 2
Exercise 2: Access all the form text box elements using arrays and access them by name.
Tip:
Live Preview
Adding data to this attribute will modify the DOM element and it will
reflect immediately on the page.
Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Inline JavaScript</title>
<script>
function update(){
document.getElementById("txtValue").innerHTML =
document.getElementById("txtName").value;
}
</script>
</head>
<body>
<h1>Update the DOM Elements</h1>
<p id="txtValue"></p>
<form>
<input type="text" id="txtName" onkeypress="update();"/>
</form>
</body>
</html>
Live Preview
Exercise 1
Exercise 1: Create two Text box and if user writes the data in one
text box then display the text in other text box.
Tip:
document.getElementsByName(“txtName”)[1].value =
document.getElementsByName(“txtName”)[0].value;
Exercise 2
Exercise 2: Show a button and when user press ask them to type
heading then change the heading with the new value.
Live Preview
You can access all the form elements using the DOM.
This is very helpful when you want to check what user has entered
the data before sending the data to server to save it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Inline JavaScript</title>
<script>
function checkFormData(){
if (inputs[i].getAttribute('type') == 'text')
{
message += inputs[i].getAttribute('name') + ": ";
message += inputs[i].value + "\n";
}
}
alert(message);
}
</script>
</head>
<body>
<form name="user" id="userfrm" action="#">
</form>
</body>
</html>
Live Preview
Exercise 1
Tip:
document.getElementById(“chkbox”).checked
Exercise 2
TIP:
<form name=”search” onsubmit=”return callFunction()” >
8 Snippets JavaScript
This snippet of code will help you to navigate the page front or back
based on the page history.
You can make the page go back and front from the JavaScript.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Snippets JavaScript</title>
<script>
function goBack(){
history.back();
}
</script>
</head>
<body>
</html>
Live Preview
Form Validation
This project will show how to validate the form using the JavaScript.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Form Validations JavaScript</title>
<script>
function checkFormData(){
var message = "";
document.getElementById("tmessage").innerHTML = message;
}
</script>
</head>
<body>
<p id="tmessage"></p>
<h1>Form Validations</h1>
<form action="https://wpfreelancer.com/" method="get">
</form>
</body>
</html>
Live Preview
This project will ask user to guess the right number between 1 to 10.
It will keep asking the number until the user guess it.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Page Description">
<title>Guess The Number</title>
<script>
do{
var input1 = prompt("Guess the Number Between 1 to 10!");
input1 = parseInt(input1);
}while(answer != input1)
</script>
</head>
<body>
</body>
</html>
Live Preview