CH3 Javascript-2
CH3 Javascript-2
BRIEF INTRODUCTION
TBS/2016201-7
Introduction
2
JavaScript is
NOT Java: the similarity in syntax is due to the C language
a scripting language : lightweight programming language
the most popular scripting language on the Internet
an interpreted language : the scripts execute without
preliminary compilation
executed on the client side: the browser
usually embedded directly into web pages
How to Insert Javascript? (1/3)
4
page.html
Result
How to Insert Javascript? (3/3)
Outside the HTML page
6
page.html
script.js
Result
Ending Statements With a Semicolon?
7
Remark:
Keywords are NOT case sensitive in javascript
e.g.: VAR , var and Var are the same keyword
JavaScript Operators (1/4)
10
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
y=2
x+y
Operators allow operation on
- Subtraction x=5 3
two or more values. y=2
Assignment Operators
Operator Example Is The Same As
/= x/=y x=x/y
%= x%=y x=x%y
JavaScript Operators (3/4)
12
Logical Operators
Operator Description Example
y=3
(x==5 || y==5)
returns false
! not x=6
y=3
!(x==y) returns
true
JavaScript Basic Examples
14
<script>
document.write("Hello World!")
</script>
<script>
alert("Hello World!")
</script>
JavaScript Basic Examples
15
<script>
x=Hello World!
document.write(x)
</script>
<script>
x=World
document.write(Hello +x)
</script>
Alert Box :
Syntax: window.alert(..) or alert(..)
<script>
alert("Hello World!")
</script>
JavaScript Popup Boxes (2/3)
17
Prompt Box
Syntax: window.prompt(..) or prompt(..)
Confirm Box
Syntax: window.confirm(..) or confirm(..)
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition1 is false and condition2 is true
}
else {
code to be executed if condition2 is false
}
Conditional Statements (3/3)
21
<script>
var x=prompt(" Enter a number ");
if(x<0)
{
alert ("You entered a negative number");
}
else
{
alert ("You entered a positive number");
}
</script>
JavaScript When is Executed?
22
Calling a JavaScript Function from
Event Handler Example
<html> image-onclick.html
<head>
<script type="text/javascript">
function test (message) {
alert(message);
}
</script>
</head>
<body>
<img src="logo.gif"
onclick="test('clicked!')" />
</body>
</html>
23
Document Object Model (DOM)
24
function changeText() {
var span = document.getElementById("output");
var textBox = document.getElementById("textbox");
textbox.style.color = "red";
} JS