Unit-II.pptx
Unit-II.pptx
Unit 2
JavaScript
PL
D
Prepared By
Assistant Professor
CSE Department, MIT SoC
JavaScript- Outline
• Overview of JavaScript
• using JS in an HTML (Embedded,
External),
• Data types,
• Control Structures,
• Arrays,
• Functions
• Objects
• Scopes
Dept. of Computer Science & Engineering.
PL
D
Overview of JavaScript,
5
Dept. of Computer Science & Engineering.
PL
D
What Can JavaScript Do?
• Can handle events
• Can read and write HTML elements
• Can validate form data
• Can access / modify browser cookies
• Can detect the user’s browser and OS
• Can be used as object-oriented language
• Can handle exceptions
• Can perform asynchronous server calls (AJAX)
7
JavaScript Advantages
• Easy to learn
• Provide rich framework
• Makes web pages more interactive
• No complications needed
• Platform independed
• Implementing form validation
• React to user actions, e.g. handle keys
• Changing an image on moving mouse over it
• Sections of a page appearing and disappearing
• Content loading and changing dynamically
• Performing complex calculations
• Custom HTML controls, e.g. scrollable table
• Implementing AJAX functionality
8
Dept. of Computer Science & Engineering.
PL
D
Dept. of Computer Science & Engineering.
PL
D
The JavaScript
Syntax
JavaScript Syntax
• JavaScript can be implemented using <script>...
</script> HTML tags in a web page.
• Place the <script> tags, within the <head> tags.
• Syntax:
• <script language="javascript" type="text/javascript">
• JavaScript code
• </script>
Dept. of Computer Science & Engineering.
PL
D
Dept. of Computer Science & Engineering.
PL
D
Dept. of Computer Science & Engineering.
PL
D
JavaScript Syntax
• The JavaScript syntax is similar to C# and Java
• Operators (+, *, =, !=, &&, ++, …)
• Variables (typeless)
•
12
Conditional statements (if, else)
• Loops (for, while)
• Arrays (my_array[]) and associative arrays (my_array['abc'])
• Functions (can return value)
• Function variables (like the C# delegates)
Enabling JavaScript in
Browsers
• JavaScript in Firefox
• Open a new tab → type about: config in the address bar.
• Then you will find the warning dialog.
• Select I’ll be careful, I promise!
• Then you will find the list of configure options in the browser.
• In the search bar, type javascript.enabled.
• There you will find the option to enable or disable javascript
by right-clicking on the value of that option → select toggle.
JavaScript - Placement in
HTML File
• There is a flexibility given to include JavaScript code anywhere
in an HTML document.
• However the most preferred ways to include JavaScript in an
HTML file are as follows −
20
Another Small Example
21
Using JavaScript Code
• The JavaScript code can be placed in:
• <script>tag in the head
• <script>tag in the body – not recommended
• External files, linked via <script>tag the head
22
• Files usually have .jsextension
• Highly recommended
• The .jsfiles get cached by the browser
JavaScript – When is Executed?
• JavaScript code is executed during the page loading or when the
browser fires an event
• All statements are executed at page loading
• Some statements just define functions that can be called later
23
• Function calls or code can be attached as "event handlers" via tag
attributes
• Executed when the event is fired by the browser
Calling a JavaScript Function from Event Handler –
Example
image-onclick.html
24
Using External Script Files
• Using external script files:
<html> external-JavaScript.html
<head>
<script src="sample.js" type="text/javascript">
</script>
The <script> tag is always empty.
25
</head>
<body>
<button onclick="sample()" value="Call JavaScript function from
sample.js" />
</body>
</html>
• External JavaScript file:
sample.js
Data Types
• JavaScript data types:
• Numbers (integer, floating-point)
• Boolean (true / false)
• String type – string of characters
26
var myName = "You can use both single or double quotes
for strings";
• Arrays
var my_array = [1, 5.3, "aaa"];
27
var test = "some string"; alert(test[7]); //
shows letter 'r'
alert(test.charAt(5)); // shows letter 's'
alert("test".charAt(1)); //shows letter 'e'
alert("test".substring(1,3)); //shows 'es'
28
alert(string1 + string2); // fat cats
• What is "9" +
9?
alert("9" + 9); // 99
29
• Appending an element / getting the last element:
arr.push(3);
var element = arr.pop();
• Reading the number of elements (array length):
arr.length;
• Finding element's index in the array:
arr.indexOf(1);
Standard Popup Boxes
• Alert box with text and [OK] button
• Just a message shown in a dialog box:
alert("Some text here");
30
• Confirmation box
• Contains text, [OK] button and [Cancel] button:
• Prompt box
• Contains text, input field with default value:
<head>
<title>JavaScript Demo</title>
32
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value); value2
=
parseInt(document.mainForm.textBox2.value); sum =
value1 + value2; document.mainForm.textBoxSum.value
= sum;
}
</script>
</head>
Sum of Numbers – Example (2)
sum-of-numbers.html (cont.)
<body>
<form name="mainForm">
<input type="text" name="textBox1" /> <br/>
<input type="text" name="textBox2" /> <br/>
33
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>
</html>
JavaScript Prompt – Example
prompt.html
price = prompt("Enter the price", "10.00"); alert('Price +
VAT = ' + price * 1.2);
34
JavaScript - Operators
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Conditional Statement (if)
unitPrice = 1.30;
if (quantity > 100) {
unitPrice = 1.20;
}
36
Symbol Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal
!= Not equal
Switch Statement
• The switch statement works like in C#:
switch (variable) { switch-statements.html
case 1:
// do something
37
break;
case 'a':
// do something else
break;
case 3.14:
// another code
break;
default:
// something completely different
}
Switch case Example
Loops
• Like in C#
• forloop
• whileloop
• do…whileloop
39
var counter;
for (counter=0; counter<4; counter++)
{
alert(counter);
}
while (counter < 5)
{
alert(++counter);
}
loops.html
While-loop Example
• <html>
• <body>
• <script type="text/javascript">
• <!-- var count = 0;
• document.write("Starting Loop ");
• while (count < 10){
• document.write("Current Count : " + count + "<br />");
count++; }
• document.write("Loop stopped!");
• //--> </script>
• <p>Set the variable to different value and then try...</p>
</body> </html>
Functions
• Code structure – splitting code into parts
• Data comes in, processed, result returned
Parameters come in
41
function average(a, b, c) here.
{
var total; Declaring variables
total = a+b+c; is optional. Type is
return total/3; never declared.
}
Value returned
here.
Function Arguments & Return Value
• Functions are not required to return a value
• When calling function it is not obligatory to specify all of its arguments
• The function has access to all the arguments passed
via argumentsarray
42
function sum() { var
sum = 0;
for (var i = 0; i < arguments.length; i ++) sum +=
parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4)
functions-demo.html
JavaScript Function Syntax
• function name(parameter1, parameter2, parameter3) {
code to be executed
}
function myFunction(a, b) {
return a * b; // Function returns the product of a
and b
}
Dept. of Computer Science & Engineering.
Objects in JS
Objects are variables too. But objects can contain many values.
PL
D
Spaces and line breaks are not important. An object initializer can span multiple lines:
Dept. of Computer Science & Engineering.
PL
D
Dept. of Computer Science & Engineering.
DOM
The document object represents the whole html document. When html document is loaded in
the browser, it becomes a document object. It is the root element that represents the html
document. It has properties and methods. By the help of document object, we can add dynamic
content to our web page.
PL
D
Dept. of Computer Science & Engineering.
PL
D
Dept. of Computer Science & Engineering.
simple example of document object that prints name with welcome message
PL
D
Assignment Title
Write a Java Script code to take inputs from user and display inputs in
following pattern