Chap 2
Chap 2
Chap 2
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6; OUTPUT
</script> My First Web Page
My First Paragraph.
</body> 11
</html>
Using document.write()
• <!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using window.alert()
• You can use an alert box to display data:
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• window.alert(5 + 6);
• </script>
• </body>
• </html>
Variables in JS
• Variables are the names given to the memory location where we can store
some values.
• 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 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.
4.JavaScript variables can also hold other types of data, like text values .
5. In JavaScript a text like "John Doe" is called a string.
6.When you assign a text value to a variable, put double or single quotes around
the value.
7.When you assign a numeric value to a variable, do not put quotes around the
value. If you put quotes around a numeric value, it will be treated as text.
Variables in JS
8.JavaScript Variables are declared using the “var” keyword. Syntax: var num; var carname;
9.JavaScript variables can be declared with initial value. Syntax: var num=1; var carname=”volvo”;
10.Multiple JavaScript variables can even be declared at the same time.
Syntax: var num=1; var name= “Bikila”;
11.Every JavaScript variables ends with semicolon (;)
Example of JavaScript variable
Let’s see a simple example of JavaScript variable.
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
Variables in JS
• JavaScript local variable
• A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only.
• For example:
<script>
function abc()
{
var x=10;//local variable
}
</script
Variables in JS
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or
declared with window object is known as global variable. For example:
<html>
<body>
<script>
var data=200;//global variable
function a(){
document.write(data);
}
function b() {
document.write(data);
}
a(); //calling JavaScript function
b();
</script>
</body>
</html>
Variables in JS
• To declare JavaScript global variables inside function, you need to use window object.
• Now it can be declared inside any function and can be accessed from any function. For
example:
• <html>
• <body>
• <script>
• function m(){
• window.value=100;//declaring global variable by window object
• }
• function n(){
• alert(window.value);//accessing global variable from other function
• }
• m();
• n(); </script> </body>
• </html>
Datatypes in JS
• 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 has dynamic types. This means that the same variable can be
used as different types.
• var x // Now x is undefined
• var x = 5; // Now x is a Number
• var x = "John"; // Now x is a String
Datatypes in JS
• There are five types of primitive data types in JavaScript. They are as follows:
• Data Type Description
• String represents sequence of characters e.g. "hello"
• Number represents numeric values e.g. 100
• Boolean represents boolean value either false or true
• Undefined represents undefined value
• Null represents null i.e. no value at all
• JavaScript non-primitive data types
• The non-primitive data types are as follows:
• Data Type Description
• Object represents instance through which we can access members
• Array represents group of similar values
• RegExp represents regular expression
Datatypes in JS
• JavaScript Arrays
• var cars=new Array();
• cars[0]="Saab";
• cars[1]="Volvo";
• cars[2]="BMW";
• or (condensed array): var cars=new Array("Saab","Volvo","BMW");
• JavaScript Objects - An object is delimited by curly braces. Inside the braces the object's
properties are defined as name and value pairs (name : value).
• The properties are separated by commas:
• var person={firstname:"John", lastname:"Doe", id:5566};
• name=person.lastname;
• name=person["lastname"];
Datatypes in JS
• Undefined and Null
• Undefined is the value of a variable with no value.
• Variables can be emptied by setting the value to null.
• cars=null;
• person=null;
• Declaring Variable Types
• When you declare a new variable, you can declare its type using the "new" keyword:
• JavaScript variables are all objects.
• When you declare a variable you create a new object.
• var carname=new String;
• var x= new Number;
• var y= new Boolean;
• var cars= new Array;
• var person= new Object;
OPERATORS
• Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and ‘+’ is called the operator.
• Operators are the symbols that perform operations on operand.
• JavaScript supports the following types of operators.
• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
• typeof Operators.
JavaScript Objects and Data Type conversion
• Everything" in JavaScript is an Object: a String, a Number, an Array, a Date.
• In JavaScript, an object is data, with properties and methods.
• In JavaScript, objects are data (variables), with properties and methods. var txt = "Hello";
Methods: txt.indexOf(),txt.length() Accessing Object Properties
• The syntax for accessing the property of an object is: objectName.propertyName
• This example uses the length property of the String object to find the length of a string:
• var message="Hello World!"; var x=message.length;
• JavaScript is a dynamically typed language
• We can convert a number in to string and vice versa
• parseInt method - used to convert a string value, which is holding a number data type
• temp = parseInt(“42”)
• anoth = parseInt(“54.34”)
• Str=””+2500;
• Str=””+temp;
• Simply adding an empty quote to a number value will convert a number into string data type.
Functions in JS
• A function consists of the “function” keyword followed by the name of the function, a set
• of open and close parentheses enclosing an optional parameter list and a body enclosed in
• a set of curly braces.
• Syntax: function functionName(parameterList)
{
// body
}
Function parameters are separated by commas in the function declaration.
• A function uses the return keyword to return a value from a function.
• JavaScript code found in a function is not executed until the function is called
• Example
function myFunction(p1, p2)
{
return p1 * p2; // The function returns the product of p1 and p2
}
Functions in JS
• Function Invocation
• The code inside the function will execute when "something" invokes (calls)
the function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
• Advantages:
• You can reuse code: Define the code once, and use it many times.
• You can use the same code many times with different arguments, to
produce different results.
Date Object
• The Date object is used to work with dates and times. Date objects are created with the Date()
constructor.
• Examples
• Get today's date.
<html>
<body>
<script>
var d=new Date();
document.write(d);
</script>
</body>
</html>
• Example:
• To store the current date in a variable called "my_date":
• var my_date=new Date()
• After creating an instance of the Date object, you can access all the methods of the object from the "my_date" variable.
• If, for example, you want to return the date (from 1-31) of a Date object, you should write the following:
• my_date.getDate()
• You can also write a date inside the parentheses of the Date() object, like this:
• new Date("Month dd, yyyy hh:mm:ss")
• new Date("Month dd, yyyy")
• new Date(yy,mm,dd,hh,mm,ss)
• new Date(yy,mm,dd)
• new Date(milliseconds)
• Here is how you can create a Date object for each of the ways above:
• var my_date=new Date("October 12, 1988 13:14:00")
• var my_date=new Date("October 12, 1988")
• var my_date=new Date(88,09,12,13,14,00)
• var my_date=new Date(88,09,12)
• var my_date=new Date(500)
ARRAY METHODS IN JS
• JavaScript Array Methods
• The Array object has many properties and methods which help developers to handle
arrays easily and efficiently. You can get the value of a property by specifying
arrayname.property and the output of a method by specifying arrayname.method().
• length property --> If you want to know the number of elements in an array, you can
use the length property.
• prototype property --> If you want to add new properties and methods, you can use
the prototype property.
• reverse method --> You can reverse the order of items in an array using a reverse
method.
• sort method --> You can sort the items in an array using sort method.
• pop method --> You can remove the last item of an array using a pop method.
• shift method --> You can remove the first item of an array using shift method.
• push method --> You can add a value as the last item of the array.
• <html>
• <head>
• <title>Arrays!!!</title>
• <script type="text/javascript">
• var students = new Array("John", "Ann", "Aaron", "Edwin", "Elizabeth");
• Array.prototype.displayItems=function(){
• for (i=0;i<this.length;i++){
• document.write(this[i] + "<br />");
• } }
• document.write("students array<br />");
• students.displayItems();
• document.write("<br />The number of items in students array is " + students.length + "<br />");
• document.write("<br />The SORTED students array<br />");
• students.sort();
• students.displayItems();
• document.write("<br />The REVERSED students array<br />");
• students.reverse();
• students.displayItems();
• document.write("<br />THE students array after REMOVING the LAST item<br />");
• students.pop();
• students.displayItems();
• document.write("<br />THE students array after PUSH<br />");
• students.push("New Stuff");
• l>
• < students.displayItems();
• document.write("<br />THE students array after PUSH<br />");
• students.push("New Stuff");
• students.displayItems();
• </script>
• </head>
• <body>
• </body>
• </html>
DOM- Document Object Model
DOM stands for Document Object Model and is responsible for how various objects
in a document interact with each other. DOM is required for developing web
pages, which includes objects like paragraphs, links, etc. These objects can be
operated to include actions like add or delete. DOM is also required to add extra
capabilities to a web page. On top of that, the use of API gives an advantage over
other existing models.
JavaScript can access all the elements in a web page using the Document Object
Model (DOM). The web browser creates a DOM of the webpage when the page is
loaded.
Using DOM, JavaScript can perform multiple tasks. It can create new elements and
attributes, change the existing elements and attributes and even remove existing
elements and attributes.
According to W3C DOM is platform language interface that allows the program and
scripts to dynamically access and update the content, structure and style of the
document.
DOM- Document Object Model
Hierarchy of Objects in web documents: DOM LEVELS
Properties and Methods of Document Object
• HTML DOM Methods are actions we can perform on
HTML elements
• HTML DOM Properties are values that we can set or
change <script>
• document.getElementById("ex").innerHTML = "Hello
World!"; </script>
• getElementById -> Method
• innerHTML -> Property
JavaScript Animation
• The JavaScript animation is implemented as gradual changing of DOM
element styles or canvas objects
• The whole process is split into pieces, and each piece is called by
timer
• An animation is created by replacing one Image frame with another
at speed such that it appears to be a moving Image
• Animations can be created using JavaScript by using a timer which
replaces one image frame with another
• The two timer function setTimeout() and setInterval() to execute
JavaScript codes at set intervals
JavaScript Animation
EVENTS IN JS
• Events are the actions that result from activities, such as clicking a link or filling a form by the user.
• An event handler is required to manage the proper execution of all these events.
• Event handlers are an extra attribute of the object. This attribute includes the event's name and the action taken if the
event takes place.
• JavaScript can also react to existing events and create new events in the page.
• getElementById, innerHTML Example
• getElementById: To access elements and attributes whose id is set.
• innerHTML: To access the content of an element.
• Event handler Example
• createElement: To create new element
• removeChild: Remove an element
• you can add an event handler to a particular element like this
• document.getElementById(id).onclick=function()
• {
• lines of code to be executed
• }
• OR
• document.getElementById(id).addEventListener("click", functionname)
• For exception handling and Regression refer w3school.com