Chapter Four
Java Script
By Tesfahun
Outline
Introduction to JavaScript
JavaScript Basic
JavaScript Syntax
Attaching JavaScript to HTML (External,
Embedded, Inline)
Basic JavaScript Input Output
JavaScript Data Types and Variables
What is DHTML?
It is a collection of technologies to create interactive pages
It is combination of a static markup language ( HTML), a
client-side scripting language (JavaScript), CSS), and the
Document Object Model (DOM)
DHTML = HTML + CSS + JavaScript
Three Legged Web Tool
JavaScript works with HTML & CSS
What is JavaScript?
Scripting language is a series of commands that are
able to be executed without the need for compiling.
It is commonly used in web development.
It is used to implement complex features on web page
It embedded in HTML
It is Client-side technology
What is JavaScript?
JavaScript allows for interactivity
Browser/page manipulation
Reacting to user actions
Simple and flexible
It was developed to add dynamic and interactive elements
to websites
Why use JavaScript?
To create dynamic and interactive Web pages
To reduce the burden server.
JavaScript runs in the browser, not on the
Web server.
Better performance
it validates the data that users enter into the
form, before it is sent to your Web application.
what JavaScript do?
To handle events
Validation of input datas
Used to access / modify browser cookies
To detect the user’s browser and OS
To handle exceptions
Perform calculations
How Does It Work?
Executes on client machine
Fast, no connection needed once loaded
programming statements combined with
HTML tags
Interpreted (not compiled)
No special tools required
When not to use JavaScript
When you need to access other resources.
Files
Programs
Databases
When you are using sensitive or copyrighted data
or algorithms.
Your JavaScript code is open to the public.
JavaScript Basic
You should place all your JavaScript code within <script> tags
(<script> and </script>)
As there are other client-side scripting languages (Example:
VBScript), it is highly recommended that you specify the
scripting language you use.
You have to use the type attribute within the <script> tag
and set its value to text/javascript like this:
<script type="text/javascript">
Cont..
Example
<html>
<head>
<title>My First JavaScript code!!!</title>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
</body>
</html>
Cont..
Example 2
to adding of two numbers
<script>
function sum(a,b)
return a + b;
var total = sum(7,11);
alert(total);
</script>
Adding JavaScript to HTML Pages
1. Embedding code
2. Inline code
3. External file
Cont..
I. Embedding code:-
<html>
<head>
<title> page title</title>
<script>
document.write("Welcome to Javatpoint");
</script>
</head>
<body>
…..
</body>
</html>
Cont..
2. inline code:-
Generally, this method is used when we have to call a
function in the HTML event attributes. There are many
cases (or events) in which we have to add JavaScript code
directly eg., OnMover event, OnClick, etc.
Cont..
Example
<!DOCTYPE html >
<html>
<head>
<title> page title</title>
</head>
<body>
<p>
<a href="#" onClick="alert('Welcome !');">Click Me</a>
</p>
<p> in this example we saw how to use inline JavaScript o
r directly in an HTML tag. </p>
</body>
</html>
Cont..
External file:-
We can also create a separate file to hold the code of
JavaScript with the (.js) extension and later
incorporate/include it into our HTML document using the
src attribute of the <script> tag.
It becomes very helpful if we want to use the same code
in multiple HTML documents.
It also saves us from the task of writing the same code over and over
again and makes it easier to maintain web pages.
…
external JavaScript
sample.js
function sample() {
alert('Hello from sample.js!')
}
JavaScript Comments
single line comments start with //
Multi-line Comments start with /* and end with */.
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().
Cont..
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:
Cont..
Example
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
Cont.…
Using document.write()
<button type="button"
<script> onclick="document.write(5 + 6)">Try
document.write(5 + 6); it</button>
</script> </body>
</body>
Cont..
Using window.alert()
<body>
<script>
window.alert(5 + 6);
</script>
</body
Cont..
window keyword.
<script>
alert(5 + 6);
</script>
JavaScript Print
<button onclick="window.print()">Print this
page</button>
JavaScript Data Types
JavaScript variables can hold different data types:
numbers, strings, objects and more
let length = 16; // Number
let lastName = "Johnson"; // String
let x = {firstName:"John",lastName:"Doe"}; //
Object
JavaScript Data Types and Variables
Variable declaration in JavaScript
Like many other programming languages, JavaScript has
variables.
JavaScript has untyped variables
Variables are declared with the var keyword:
var name; // declaring single variable
var name, title, num; // declaring multiple
variables
var name = "Harsh"; // initializing variables
name = "Rakesh"; // initializing variables
Events
JavaScript is event-driven.
JavaScript defines various events:
onClick – link or image is clicked
onSubmit – a form is submitted
onMouseOver – the mouse cursor moves over it
onLoad – something gets loaded in the browser
Events are specified in the HTML code
Cont..
Reading assignment
JavaScript datatype conversation
• Converting Numbers to Strings
• Converting Booleans to Numbers
• Converting Booleans to Strings
JavaScript Arithmetic Operators
Operator Description Example
+ Addition let x = 100 + 50;
document.getElementById("demo").innerHTML = x;
- Subtraction let z = 5-2;
document.getElementById("demo").innerHTML = z;
* Multiplicati >>
on
** Exponentiat let z = 5 ** 2;
ion (ES2016 document.getElementById("demo").innerHTML = z;
)
/ Division
% Modulus
(Remainder)
++ Increment
-- Decrement
Comparison Operators
Logical operator
Cont..
Part II
Loading
Conditional and Looping Statements
• Control structure actually controls the
flow of execution of a program. Following
are the several control structure
supported by javascript.
if … else
switch case
do while loop
while loop
for loop
if Statement
IF statement is a conditional branching statement.
In 'IF' statement, if the condition is true a group of
statement is executed. And if the condition is false, the
following statement is skipped.
• Syntax : If statement
if(condition)
{
//Statement 1;
//Statement 2;
}
Example
<html>
<body>
<script type="text/javascript">
var num = prompt("Enter Number");
if (num > 0)
{
alert("Given number is Positive!!!");
}
</script>
</body>
</html>
If – Else Statement
If – Else is a two-way decision statement.
It is used to make decisions and execute statements
conditionally.
Syntax
if (condition)
{
//Statement 1;
}
else if(condition)
{
//Statement 2;
}
else
{
//Statement 3;
}
Switch Statement
Switch is used to perform different actions on different
conditions.
It is used to compare the same expression to several
different values.
Cont..
Syntax
switch(expression)
{
case condition 1:
//Statements;
break;
case condition 2:
//Statements;
break;
case condition 3:
//Statements;
break;
.
.
case condition n:
//Statements;
break;
default:
//Statement;
}
Example
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7");
switch (day)
{
case (day="1"):
document.write("Sunday");
break;
case (day="2"):
document.write("Monday");
break;
case (day="3"):
document.write("Tuesday");
break;
default:
document.write("Invalid Weekday");
break;
}
</script>
For Loop
For loop is a compact form of looping.
It includes three important parts:
1. Loop Initialization
2. Test Condition
3. Iteration
Cont..
Syntax
for(initialization; test-condition; increment/decrement)
//Statements;
}
While Loop
While loop is an entry-controlled loop statement.
It is the most basic loop in JavaScript.
It executes a statement repeatedly as long as
expression is true.
Once the expression becomes false, the loop
terminates
Syntax
while (condition)
//Statements;
}
Do-While Loop
Do-While loop is an exit-controlled loop statement.
Similar to the While loop, the only difference is condition
will be checked at the end of the loop.
The loop is executed at least once, even if the condition is
false.
Syntax
do
{
//Statements;
}
while(condition);
Cont.…
<script type ="text/javascript">
var i = 0;
do
{
document.write(i+"<br>")
i++;
}
while (i <= 5)
</script>
Array in JavaScript
What is array ?
An array is a special variable, which can hold more than one
value:
JavaScript array is an object that represents a collection of
similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2.By creating instance of Array directly (using new keyword)
3.By using an Array constructor (using new keyword)
JavaScript array literal
• The syntax of creating array using array literal is given
below:
var arrayname=[value1,value2.....valueN];
<script>
var name=[“Aman",“Helen",“Meklit","Tesfahun"];
for (i=0;i<name.length;i++)
{
document.write(name[i] + "<br/>");
}
</script>
JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
<script>
var i;
var animal = new Array();
animal[0] = "cat";
animal[1] = "dog";
animal[2] = "sheep";
for (i=0;i< animal.length;i++)
{
document.write(animal[i] + "<br>");
}
</script>
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.
<script>
var temp=new Array("Jai","Vijay","Smith");
for (i=0;i< temp.length;i++){
document.write(temp[i] + "<br>");
}
</script>
Java script function
A function is a block of code that performs a specific
task.
A function is a group of reusable code which can be called
anywhere in your program
JavaScript allows us to write our own functions
Declare a function
To declare a function, you use the function keyword,
followed by the function name, a list of parameters,
and the function body as follows:
function functionName(parameters)
// function body
}
Calling a function
To use a function, you need to call it.
Calling a function is also known as invoking a function.
To call a function, you use its name followed by arguments
enclosing in parentheses like this:
functionName(arguments);
what is the differences between argument and
parameters ????
Example
// declaring a function // declaring a function
function cs() {
function greet(name) {
console.log(“hello Student !");
document.write("Hello " + name +
}
":");}
// calling the function
// calling cs();
greet("Tesfahun ");
JavaScript DOM (Document object Model)
What is the DOM?
The HTML DOM defines a standard way for accessing and
manipulating HTML documents.
JavaScript uses the HTML Document Object Model to
manipulate HTML.
The DOM is a hierarchy of HTML things.
The DOM presents an HTML document as a tree-structure
Cont..
Cont..
Different ways to access HTML elements using JavaScript
Sometimes, users need to manipulate the HTML element
without changing the code of the HTML.
In this scenario, users can use JavaScript to change
HTML elements without overwriting them.
Before we move ahead to change the HTML element
using JavaScript, users should learn to access it from
the DOM (Document Object Model).
Cont..
From the DOM, users can access HTML elements in five
different ways in JavaScript.
1. Get HTML element by Id
2. Get HTML element by className
3. Get HTML element by Name Read how does it
works
4. Get HTML element by tagName
5. Get HTML element by CSS Selector
Example
<body>
<p id="intro">Finding HTML Elements by Id</p>
<p id="demo"></p>
<script>
const element = document.getElementById("intro");
document.getElementById("demo").innerHTML =
element.innerHTML;
</script>
</body>
JavaScript Window
The window object is the Global object
The global object of JavaScript in the browser is the
window object.
It means that all variables and functions declared globally
with the var keyword become the properties and methods of
the window object.
Cont..
1) Window size
<body>
<h2>JavaScript Window</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
window.innerWidth + "px<br>" +
window.innerHeight + "px";
</script>
</body>
Cont..
Some other methods
window.open() - open a new window
window.open(url, windowName,[windowFeatures]);
window.moveTo() - move the current window
window.moveTo(x, y);
window.resizeTo() - resize the current window
window.resizeTo(width,height);
Cont..
Window Location Href The window.location.href property
returns the URL of the current page
<body>
<h3>The window.location object</h3>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The full URL of this page is:<br>" +
window.location.href;
</script>
</body>
Output
HTML Forms and JavaScript
JavaScript is very good at processing user input in the web
browser
HTML <form> elements receive input
Forms and form elements have unique names
Each unique element can be identified
Uses JavaScript Document Object Model (DOM)
•
Form validation
JavaScript provides a way to validate form's data
on the client's computer before sending it to the
web server
Form validation generally performs two functions.
• Basic Validation
checked to make sure all the mandatory fields are filled
in.
It would require just a loop through each field in the
form and check for data.
• Data Format Validation
• the data that is entered must be checked for correct
form and value.
• Your code must include appropriate logic to test
correctness of data.
Cont..
cont…
Thanks
?