Introduction To Javascript Instructor: Engr. Laila Nadeem: Pat Morin Comp240 5
Introduction To Javascript Instructor: Engr. Laila Nadeem: Pat Morin Comp240 5
COMP240
Introduction
5 to
JavaScript
Instructor : Engr. Laila Nadeem
Outline
• What is JavaScript?
– History
– Uses
• Adding JavaScript to HTML
• JavaScript syntax
• JavaScript events
• JavaScript classes
3
JavaScript is not Java
4
What can JavaScript Do?
5
Pros and Cons of JavaScript
• Pros:
– Allows more dynamic HTML pages, even complete web
applications
Cons:
–•Requires a JavaScript-enabled browser
– Requires a client who trusts the server enough to run the code
the server provides
6
Hello World in JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>
</body>
</html>
7
Hello World Screenshot
8
External Scripts
9
Using JavaScript in your HTML
<html>
<head>
<title>Hello World in JavaScript</title>
<script type="text/javascript">
function helloWorld() {
document.write("Hello World!");
}
</script>
</head>
<body>
<script type="text/javascript">
helloWorld();
</script>
</body>
</html>
10
The <script>…</script> tag
<script type="text/javascript">
.
.
.
</script>
11
Displaying text
The document.write() method writes a string of text to the
browser
<script type="text/javascript">
<!--
document.write("<h1>Hello, world!</h1>");
//-->
</script>
12
document.write()
Ends in a semicolon
document.write("<h1>Hello,world!</h1>");
13
Comments in JavaScript
Two types of comments
Single line
Uses two forward slashes (i.e. //)
Multiple line
Uses /* and */
14
Single Line Comment Example
<script type="text/javascript">
<!--
// This is my JavaScript comment
document.write("<h1>Hello!</h1>");
//-->
</script>
15
Multiple Line Comment Example
<script type="text/javascript">
<!--
/* This is a multiple line comment.
* The star at the beginning of this line is optional.
* So is the star at the beginning of this line.
*/
document.write("<h1>Hello!</h1>");
//-->
</script>
16
Find the Bug!
<script type="text/javascript">
<!--
/* This is my JavaScript comment
* that spans more than 1 line.
*
document.write("<h1>Hello!</h1>");
//-->
</script>
17
Arrays
JavaScript array is an object that represents a collection of
similar type of elements.
There are 3 ways to construct array in JavaScript
By array literal
By creating instance of Array directly (using new
keyword)
By using an Array constructor (using new keyword)
1. Array Literal
<script>
var emp=["Ali","Atif","Ahmed"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2. Using New Keyword
<script>
var i;
var emp = new Array();
emp[0] = "Ali";
emp[1] = "Atif";
emp[2] = "Ahmed";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3. Array Constructor
<script>
var emp=new Array("Ali","Atif","Ahmed");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>