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

WT PPT U2

JavaScript is used to create dynamic client-side pages. It is an object-based scripting language that enables dynamic interactivity on websites when applied to an HTML document. JavaScript code can be placed between script tags in HTML documents or external .js files. Common data types in JavaScript include strings, numbers, booleans, objects, arrays, and null/undefined. JavaScript contains operators, conditional statements like if/else, loops, and functions to manipulate data and perform tasks. Objects are fundamental data structures in JavaScript that group together properties and methods. Arrays are objects that hold multiple values of the same type.

Uploaded by

Life and Journal
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)
71 views

WT PPT U2

JavaScript is used to create dynamic client-side pages. It is an object-based scripting language that enables dynamic interactivity on websites when applied to an HTML document. JavaScript code can be placed between script tags in HTML documents or external .js files. Common data types in JavaScript include strings, numbers, booleans, objects, arrays, and null/undefined. JavaScript contains operators, conditional statements like if/else, loops, and functions to manipulate data and perform tasks. Objects are fundamental data structures in JavaScript that group together properties and methods. Arrays are objects that hold multiple values of the same type.

Uploaded by

Life and Journal
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/ 51

Unit-II

JavaScript
JavaScript

► JavaScript is used to create client-side dynamic pages.


► JavaScript is an object-based scripting language.
► It is an interpreted, full-fledged programming language that enables dynamic
interactivity on websites when applied to an HTML document.
► Although, JavaScript has no connectivity with Java programming language.
Features of JavaScript

1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language.
3. JavaScript is a weakly typed language(dynamic typed), where certain types are
implicitly cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than
using classes for inheritance.
5. It is a case-sensitive language.
First JavaScript Example
<!doctype>
<html>
<head>
<title> Fisrt Java Script Example </title>
</head>
<body>
<script>
document.write("hello world");
</script>
</body>
</html>
► The script tag specifies that we are using JavaScript.
► The document. write() function displays dynamic content through JavaScript.
► 3 Places to put JavaScript code
1. Between the body tag of HTML
2. Between the head tag of HTML
3. In .js file (external JavaScript)
External JavaScript file

► We can create external JavaScript file and embed it in many HTML pages.
► It provides code re-usability because a single JavaScript file can be used in several
HTML pages.
► An external JavaScript file must be saved by a .js extension.
► It is recommended to embed all JavaScript files into a single file. It increases the speed
of the webpage.
► The length of the code reduces as only we need to specify the location of the js file.
► If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
► The web browser needs to make an additional http request to get the js code.
► A tiny to a large change in the js code may cause unexpected results in all its dependent
files.
► If it is a few lines of code, then better to implement the internal javascript code.
JavaScript Variable

► A JavaScript variable is simply the name of a storage location.


► There are two types of variables in JavaScript: local variable and global variable.
► There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After the first letter we can use digits (0 to 9), for example, value1.
3. JavaScript variables are case-sensitive, for example, x and X are different variables.
Example

<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
Javascript Data Types
► JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
► JavaScript primitive data types
► There are five types of primitive data types in JavaScript. They are as follows:
► String: represents a sequence of characters e.g. "hello"
► Number: represents numeric values e.g. 100
► Boolean: represents boolean value either false or true
► Undefined: represents an undefined value
► Null: represents null i.e. no value at all
► JavaScript non-primitive data types
► The non-primitive data types are as follows:
► Object: represents instance through which we can access members
► Array: represents a group of similar values
► RegExp: represents regular expression
JavaScript Operators

► Operators are symbols that are used to perform operations on operands.


► There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
Arithmetic Operators

Operator Description Example


+ Addition 10+20 = 30
- Subtraction 20-10 = 10
* Multiplication 10*20 = 200
/ Division 20/10 = 2
% Modulus (Remainder) 20%10 = 0
++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9


Comparison Operators
Operator Description Example

== Is equal to 10==20 = false

!= Not equal to 10!=20 = true

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false


Bitwise Operators

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10


<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2
Logical Operators

Operator Description Example

&& Logical AND (10==20 && 20==33) =


false

|| Logical OR (10==20 || 20==33) =


false

! Logical Not !(10==20) = true


Assignment Operators
Operator Description Example

= Assign X= 20
+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a =


200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0


JavaScript If-else

► There are three forms of if statement in JavaScript.


1. If Statement
2. If else statement
3. if else if statement
► If statement
if(expression){
//content to be evaluated
}
Example

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
If...else Statement

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
If...else if statement
<script>
var a=20;
if(a==10){
document.write("a is equal to 10"); }
else if(a==15){
document.write("a is equal to 15"); }
else if(a==20){
document.write("a is equal to 20"); }
else{
document.write("a is not equal to 10, 15 or 20"); }
</script>
► Switch statement is used to execute one code from multiple expressions.
► Syntax:
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
default:
code to be executed if above values are not matched;
}
Example
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade"; }
document.write(result);
</script>
JavaScript Loops

► There are four types of loops in JavaScript.


1. for loop
2. while loop
3. do-while loop
For loop

<script>
for (var i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
While loop

<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
do while loop

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
JavaScript Functions

► function keyword is used to define functions.


<script>
function msg(){
Document.write("hello! this is message");
}
msg();
</script> (or we can call in this way)
<form>
<input type="button" onclick="msg()" value="call function"/>
</form>
Function With Arguments

<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
JavaScript Function Object

► We can also create functions as objects.


► It executes the code globally. However, if we call the constructor directly, a function is
created dynamically but in an unsecured way.
► Syntax
new Function (“arg1”,”arg2”,----- , “function body”)
<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>
Objects in JavaScript

► A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
► JavaScript is an object-based language. Everything is an object in JavaScript.
► JavaScript is template-based not class-based. Here, we don’t create a class to get the
object. But, we direct create objects.
► Creating Objects in JavaScript
► There are 3 ways to create objects.
1. By object literal
2. By creating an instance of an Object directly (using new keyword)
3. By using an object constructor (using new keyword)
JavaScript Object by object literal

<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By creating instance of Object

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By using an Object constructor
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
JavaScript Array

► avaScript array is an object that represents a collection of similar type of elements.


► There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
JavaScript array literal

<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
JavaScript Array directly (new keyword)

<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript array constructor (new
keyword)
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript String

► The JavaScript string is an object that represents a sequence of characters.


► There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
► var str="This is string literal";
► var stringname=new String("string literal");
JavaScript Math

► The JavaScript math object provides several constants and methods to perform
mathematical operation.

► document.write(Math.sqrt(25))
► document.write(Math.random())
► document.write(Math.pow(2,5))
► document.write(Math.floor(25.56))
► document.write(Math.ceil(25.56))
► document.write(Math.round(2.6))
► document.write(Math.abs(-25))
Browser Object Model (BOM)

► The Browser Object Model (BOM) is used to interact with the browser.
► The default object of the browser is window means you can call all the functions of the
window by specifying window or directly.
► For example: window.alert("hello");
► Window Object : The window object represents a window in browser. An object of
window is created automatically by the browser.
► Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.
Methods of window object

Method Description
alert() displays the alert box containing message with ok
button.
confirm() displays the confirm dialog box containing
message with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open(“url”) opens the new window.


close() closes the current window.
setTimeout() performs action after specified time like calling
function, evaluating expressions etc.
setTimeout(
function()
{
document.write("hello")},2000);
Document Object Model

► 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.
Methods of document object
► We can access and change the contents of a document by its methods.

Method Description

write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with newline


character at the end.

getElementById() returns the element having the given id value.

getElementsByName() returns all the elements having the given name value.

getElementsByTagName() returns all the elements having the given tag name.

getElementsByClassName() returns all the elements having the given class name.
DOM event handling

► HTML DOM allows JavaScript to react to HTML events:


► A JavaScript can be executed when an event occurs, like when a user
clicks on an HTML element.
► To execute code when a user clicks on an element, add JavaScript
code to an HTML event attribute:
► Examples of HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
Example

► In this example, the content of the <h1> element is changed when a user
clicks on it:

<body>
<h1 onclick="this.innerHTML = 'sorry'">Click here</h1>
</body>
► In this example, a function is called from the event handler:
► <body>

<h1 onclick="changeText(this)">Click on this text!</h1>

<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
Mouse hover event
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body>

You might also like