Web Programming
Chapter Four
JavaScript
By
Tesfahun
Outline
✓ Introduction to JavaScript
✓ JavaScript Basic
▪ JavaScript Syntax
▪ Attaching JavaScript to HTML (External,
Embedded, Inline)
✓ JavaScript Comments
✓ 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 (Cascading Style
Sheets)
➢Content is separated from Presentation & Behavior
What is JavaScript?
➢Scripting language is a series of commands that are able to
be executed without the need for compiling.
➢JavaScript is a programming language commonly used
in web development.
➢It is programming language which 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
Cont..
➢JavaScript code can be inserted anywhere within the
HTML of a webpage
➢Eg
➢JavaScript function may check a web form before it is
submitted to make sure all the required fields have
been filled out.
➢The JavaScript code can produce an error message
before any information is actually transmitted to the
server.
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?
❖ Embedded within HTML page
❖ Executes on client machine
➢ Fast, no connection needed once loaded
❖ Simple 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 F i r s t JavaScript c o d e ! ! ! < / t i t l e >
<script ty pe="text/ j a vascript">
a le r t("H ello 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>
Embedding JavaScript in HTML
➢ To add dynamic user experience (e.g. popup, alert
message, animations etc.) to an HTML document you can
add JavaScipt to your HTML document.
➢ Html script element is used to enclose client side scripts
like JavaScript within an HTML document
<script>
JavaScript statements.......
</script>
Cont..
➢There are three main types of attributes in script
element
1. Language
<script language = "JavaScript1.2"> ..</script>
2. src <script src = "common.js"> JavaScript
statements....... </script>
3. Type script type="text/javascript"> JavaScript
statements....... </script>
Adding JavaScript to HTML Pages
1. Embedding code
2. Inline code
3. External file
Cont..
➢ I. Embedding code:-
<html>
<head>
< t i t l e > page t i t l e < / t i t l e >
<script>
document.write("Welcome t o J a v a t p o i n t " ) ;
</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>
< t i t l e > page t i t l e < / t i t l e >
</head>
<body>
<p>
<a h r e f ="#" onClick="alert('Welcome ! ' ) ; " > C l i c k Me</a>
</p>
<p> i n t h i s exampl e we saw how to use i n l in e JavaScrip t o
r d i r e c t l y i n an HTML t a g . </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
function sample() {
a l e r t ( ' H e l l o 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 F i r s t Web Page</h1>
<p>My F i r s t Paragraph</p>
<p id="demo"></p>
<script>
documen t. getElementByI d ( "d emo") . i nnerHTML = 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.ale r t ( 5 + 6) ;
</script>
</body
Cont..
➢ window keyword.
< script >
alert(5 + 6);
</script>
➢ JavaScript Print
<button o n c l ick="window.print( ) " > Pri n t t h is
page</button>
JavaScriptDataTypes
➢ JavaScript variables can hold different data types:
numbers, strings, objects and more
l e t length = 16; / / Number
l e t lastName = "Johnson"; / / String
l e t x = { f i r stName: " J ohn" , l a s tName : " 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, t i t l e , num; / / declaring multiple
variables
✓ var name = "Harsh"; / / in i t i a l i zin g v a r iables
✓ name = "Rakesh"; / / i n i t i a l i z i n g 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
JavaScriptArithmeticOperators
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 document.getElementById("demo").innerHTML = z;
(ES2016)
/ Division
% Modulus
(Remainder)
++ Increment
-- Decrement
Comparison Operators
Logical operator
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");
i f (num > 0 )
{
a l e r t ( " G i v e n number i s P o s i t i v e ! ! ! " ) ;
}
</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
i f (condition)
{
//Statement 1 ;
}
else i f ( c o n d i t i o n )
{
//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 c o n d itio n 1 :
//Statements;
break;
case c o n d itio n 2 :
/ /Stateme n ts;
break;
case c o n d itio n 3 :
/ /Stateme n ts;
break;
.
.
case c o n d itio n n :
/ /Stateme n ts;
break;
default:
//Sta te men t;
Example
<script type="text/javascript">
var day = prompt("Enter a number between 1 and 7 " ) ;
switch (day)
{
case ( d a y= " 1 " ) :
document . wr i t e( " Sunday" ) ;
break;
case ( d a y= " 2 " ) :
document.write("Monday");
break;
case ( d a y= " 3 " ) :
document.write("Tuesday");
break;
default:
document . writ e("I nvalid 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
f o r ( i n i t i a l i z a t i on; t e s t- con d it i o n ; in cre me n t /decremen t )
//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>
Cont..
Part II
Loading
Thanks
?