0% found this document useful (0 votes)
6 views

Unit-II.pptx

This document provides an overview of JavaScript, covering its importance in web development, syntax, data types, control structures, and functions. It outlines how to embed JavaScript in HTML, its capabilities such as handling events and form validation, and includes examples of JavaScript code. Additionally, it discusses the Document Object Model (DOM) and provides a student assignment related to JavaScript programming.

Uploaded by

tusharmhans
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Unit-II.pptx

This document provides an overview of JavaScript, covering its importance in web development, syntax, data types, control structures, and functions. It outlines how to embed JavaScript in HTML, its capabilities such as handling events and form validation, and includes examples of JavaScript code. Additionally, it discusses the Document Object Model (DOM) and provides a student assignment related to JavaScript programming.

Uploaded by

tusharmhans
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Dept. of Computer Science & Engineering.

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,

• JavaScript is a language that is largely used in the world wide


web to add client side interactivity to web pages.

• JavaScript is one of the 3 languages all web developers must


learn:
• 1. HTML to define the content of web pages
• 2. CSS to specify the layout of web pages
• 3. JavaScript to program the behavior of web pages
• JavaScript is a very powerful client-side scripting language.
• Javascript is a dynamic computer programming language.

JavaScript
• JavaScript is a front-end scripting language developed by
Netscape for dynamic content
• Lightweight, but with limited capabilities
• Can be used as object-oriented language
• Client-side technology
• Embedded in your HTML page
• Interpreted by the Web browser
• Simple and flexible
• Powerful to manipulate the DOM

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 −

• Script in <head>...</head> section.


• Script in <body>...</body> section.
• Script in <body>...</body> and <head>...</head> sections.
• Script in an external file and then include in
<head>...</head> section.
JavaScript in <head>...</head> section
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") }
//--> </script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

• This code will produce the following results −


JavaScript in <body>...</body> section
<html>
<head> </head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

• This code will produce the following results



Hello World
This is web page body
JavaScript in <body> and <head>
<html>
<head>
<script type="text/javascript">
<!-- function sayHello()
{ alert("Hello World") } //-->
</script>
</head>
<body>
<script type="text/javascript">
<!-- document.write("Hello World") //-->
</script>
<input type="button" onclick="sayHello()" value="Say Hello"
/>
</body> </html>

• This code will produce the following result −


JavaScript in External File
• HTML File
<html>
<head>
<script type="text/javascript"
src="filename.js" >
</script>
</head>
<body> ....... </body>
</html>

• JavaScript File – filename.js


function sayHello()
{ alert("Hello World") }
The First Script

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"];

• Associative arrays (hash tables)


var my_hash = {a:2, b:3, c:"text"};
Everything is Object
• Every variable can be considered as object
• For example strings and arrays have member functions:
objects.html

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'

var arr = [1,3,4];


alert (arr.length); // shows 3 arr.push(7); // appends
7 to end of array alert (arr[3]); // shows 7
String Operations
• The +operator joins strings

string1 = "fat ";


string2 = "cats";

28
alert(string1 + string2); // fat cats

• What is "9" +
9?
alert("9" + 9); // 99

• Converting string to number:


alert(parseInt("9") + 9); // 18
Arrays Operations and Properties
• Declaring new empty array:
var arr = new Array();
• Declaring an array holding few elements:
var arr = [1, 2, 3, 4, 5];

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:

confirm("Are you sure?");

• Prompt box
• Contains text, input field with default value:

prompt ("enter amount", 10);


JavaScript Variables
<script type="text/javascript">
<!--
var name = "Amit";
var money;
money = 2000.50;
//-->
</script>
Sum of Numbers – Example
sum-of-numbers.html
<html>

<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
}

• var x = myFunction(4, 3); // Function is called, return value


will end up in x

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.

const car = {type:"Fiat", model:"500", color:"white"};

Creating a JavaScript Object

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.

it is the object of window. So


PL
D
window.document
Is same as
document
Dept. of Computer Science & Engineering.

Properties of document object: can be accessed and modified


by the document object.

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

Hello………………Welcome to the …………….World of Javascript


Welcome to MIT Art Design and Technology University, Pune
Students Tasks

1.Write a Javascript for Inputting Given details


2.Make Use of Appreciate HTML form and
Tags
3.Make use of CSS if requires
4.Show output as per requirement in assignment
title
THANK YOU

You might also like