JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16...

44
JavaScript is an object-based scripting language that is lightweight and cross-platform. Jun 15, 2022 JavaScript

description

JavaScript is used to create interactive websites 3 Client-side validation Dynamic drop-down menus Displaying data and time Displaying popup windows and dialog boxes (like alert dialog box, confirm dialog box and prompt dialog box) Displaying clocks etc.

Transcript of JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16...

Page 1: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript is an object-based scripting language that is lightweight

and cross-platform.

May 3, 2023

JavaScript

Page 2: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

About JavaScript

2

JavaScript is not Java, or even related to JavaThe original name for JavaScript was “LiveScript”The name was changed when Java became popularNow that Microsoft no longer likes Java, its name for their

JavaScript dialect is “Active Script”Statements in JavaScript resemble statements in

Java, because both languages borrowed heavily from the C languageJavaScript should be fairly easy for Java programmers to learnHowever, JavaScript is a complete, full-featured, complex

languageJavaScript is seldom used to write complete

“programs”Instead, small bits of JavaScript are used to add functionality

to HTML pagesJavaScript is often used in conjunction with HTML “forms”

JavaScript is reasonably platform-independent

Page 3: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript is used to create interactive websites

3

Client-side validationDynamic drop-down menusDisplaying data and timeDisplaying popup windows and dialog

boxes (like alert dialog box, confirm dialog box and prompt dialog box)

Displaying clocks etc.

Page 4: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Referring to external java script file <html>   <head>   <script type="text/javascript" src="message.js"></script>   </head>   <body>   <p>Welcome to JavaScript</p>   <form>   <input type="button" value="click" onclick="msg()"/>   </form>   </body>   </html>   external JavaScript file that prints Hello in a alert dialog box. message.js function msg(){    alert("Hello");   }  

4

Page 5: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Using JavaScript in a browser

5

JavaScript code is included within <script> tags inside a HTML page or we can create a seperate java script file ending with js extension and keep our code there:<script type="text/javascript">

……………………….</script>

Notes:The type attribute is to allow you to use other scripting

languages (but JavaScript is the default)This simple code does the same thing as just putting <h1>Hello

World!</h1> in the same place in the HTML documentThe semicolon at the end of the JavaScript statement is optional

You need semicolons if you put two or more statements on the same line

It’s probably a good idea to keep using semicolons

Page 6: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript isn’t always available

6

Some old browsers do not recognize script tags as browser need a java script engine to execute java script.These browsers will ignore the script tags but will display the

included JavaScriptTo get old browsers to ignore the whole thing, use:

<script type="text/javascript"> <!-- document.write("Hello World!") --> </script>

<!-- This is treated as a one-line JS commentSome users turn off JavaScript

Use the <noscript>message</noscript> to display a message in place of whatever the JavaScript would put there

Page 7: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Where to put JavaScript

7

JavaScript can be put in the <head> or in the <body> of an HTML documentJavaScript functions should be defined in the <head>

This ensures that the function is loaded before it is neededJavaScript in the <body> will be executed as the page loads

JavaScript can be put in a separate .js file<script src="myJavaScriptFile.js"></script>Put this HTML wherever you would put the actual JavaScript

codeAn external .js file lets you use the same JavaScript on multiple

HTML pagesThe external .js file cannot itself contain a <script> tag

JavaScript can be put in an HTML form object, such as a buttonThis JavaScript will be executed when the form object is used

Page 8: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript VariablesA JavaScript 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).Name must start with a letter (a to z or A to Z),

underscore( _ ), or dollar( $ ) sign.After first letter we can use digits (0 to 9), for

example value1.JavaScript variables are case sensitive, for

example x and X are different variables.var x = 10;  var _value=“xyz";  

8

Page 9: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

 Data types

9

There are two types of data types in JavaScript.Primitive data typeNon-primitive data typeNote:JavaScript is a dynamic type language,

means you don't need to specify type of the variable because it is dynamically used by JavaScript engine. You need to use varhere to specify the data type. It can hold any type of values such as numbers, strings etc. For example:

var a=40;//holding number  var b=“xyz";//holding string

Page 10: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript primitive data types

10

There are five types of primitive data types in JavaScript. They are as follows:

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 valueNull represents null i.e. no value at all

Page 11: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

The non-primitive data types are as follows

11

Object represents instance through which we can access members

Array represents group of similar valuesRegExp represents regular expression

Page 12: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Variables

12

Variables are declared with a var statement:variable is simply a name of storage location.

var pi = 3.1416, x, y, name = "Dr. Dave" ;Variables names must begin with a letter or underscore Variable names are case-sensitive Variables are untyped (they can hold values of any

type)The word var is optional (but it’s good style to use it)

Variables declared within a function are local to that function (accessible only within that function)

Variables declared outside a function are global (accessible from anywhere on the page)

Page 13: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Operators in JavaScript

13

.Arithmetic OperatorsComparison (Relational) OperatorsBitwise OperatorsLogical OperatorsAssignment OperatorsSpecial Operators

Page 14: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Operators, I

14

Because most JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it

Arithmetic operators (all numbers are floating-point): + - * / % ++ --

Comparison operators: < <= == != >= >

Logical operators: && || ! (&& and || are short-circuit operators)

Bitwise operators: & | ^ ~ << >> >>>

Assignment operators: += -= *= /= %= <<= >>= >>>= &= ^= |=

Page 15: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Operators, II

15

String operator: +

The conditional operator: condition ? value_if_true : value_if_false

Special equality tests:== and != try to convert their operands to

the same type before performing the test=== and !== consider their operands

unequal if they are of different types Additional operators (to be discussed):

new typeof void delete

Page 16: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Comments

16

Comments are as in C or Java:Between // and the end of the lineBetween /* and */

Java’s javadoc comments, /** ... */, are treated just the same as /* ... */ comments; they have no special meaning in JavaScript

Page 17: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Function

17

We can call function by passing arguments. Let’s see the example of function that has one argument.

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

be(4)"/>  </form>  

Page 18: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Function with Return Value

18

We can call function that returns a value and use it in our program. Let’s see the example of function that returns value.

<script>  function getInfo(){  return "hello javatpoint! How r u?";  }  </script>  <script>  document.write(getInfo());  </script>  

Page 19: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript if-else statement

19

The JavaScript if-else statement is used to execute the code whether condition is true or false.

There are three forms of if statement in JavaScript.

If StatementIf else statementif else if statement

Page 20: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Statements, I

20

Most JavaScript statements are also borrowed from CAssignment: greeting = "Hello, " + name;Compound statement:

{ statement; ...; statement }If statements:

if (condition) statement; if (condition) statement; else statement;

Familiar loop statements: while (condition) statement; do statement while (condition); for (initialization; condition; increment) statement;

Page 21: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Statements, II

21

The switch statement: switch (expression) { case label : statement; break; case label : statement; break; ... default : statement; }

Other familiar statements:break;continue;The empty statement, as in ;; or { }

Page 22: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript Objects

22

•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 class to get the object. But, we direct create objects.

Page 23: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Creating Objects in JavaScript

23

•There are 3 ways to create objects.•By object literal•By creating instance of Object directly (using new keyword)•By using an object constructor (using new keyword)

Page 24: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

using an Object constructor

24

Here, you need to create function with arguments. Each argument value can be assigned in the current object by using this keyword.

The this keyword refers to the current object.<script>  function emp(id,name,salary){  this.id=id;  this.name=name;  this.salary=salary;  }  e=new emp(103,"Vimal Jaiswal",30000);    </script>  

Page 25: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

The syntax of creating object using object literal

25

object={property1:value1,property2:value2.....propertyN:valueN}  

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

Page 26: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

By creating instance of Object The syntax of creating object directly is given below:var objectname=new Object();  Here, new keyword is used to create object.Let’s see the example of creating object directly.<script>  var emp=new Object();  emp.id=101;  emp.name="Ravi Malik";  emp.salary=50000;  document.write(emp.id+" "+emp.name+" "+emp.sal

ary);  </script>  

26

Page 27: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Objects in javascript

27

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

The JavaScript date object can be used to get year, month and day. You can display a timer on the webpage by the help of JavaScript date object.

Page 28: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Creating instance of Object

28

The syntax of creating object directly is given below:

var objectname=new Object();  Here, new keyword is used to create object.Let’s see the example of creating object directly.<script>  var emp=new Object();  emp.id=101;  emp.name="Ravi Malik";  emp.salary=50000;  document.write(emp.id+" "+emp.name+" "+emp.s

alary);  </script>  

Page 29: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript Array

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

JavaScript array literalThe syntax of creating array using array literal

is given below:var arrayname=[value1,value2.....valueN];  As you can see, values are contained inside [ ]

and separated by , (comma).Let’s see the simple example of creating and

using array in JavaScript. 

29

Page 30: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

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

30

Page 31: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript String

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

There are 2 ways to create string in JavaScriptFirst way by string literalThe string literal is created using double

quotes. The syntax of creating string using string literal is given below:

var stringname="string value";  

31

Page 32: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Second way to create string string object (using new keyword)The syntax of creating string object using

new keyword is given below:var stringname=new String("string literal");

  

32

Page 33: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript Math Object

The JavaScript math object provides several constants and methods to perform mathematical operation. Unlike date object, it doesn't have constructors.

Math.sqrt(n)The JavaScript math.sqrt(n) method returns

the square root of the given number.Math.random()The JavaScript math.random() method

returns the random number between 0 to 1.

33

Page 34: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

The HTML DOM (Document Object Model

34

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

This step actually happens before contents are actualluy painted on browser.

Page 35: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Continued

35

DOM is a standard defined by w3cAPI are defined by w3c. And implemented

by different browser vendors We can use different methods to

manipuate DOM objects .Since different html elements are

represented as objects of DOM.

Page 36: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

What is the DOM?

36

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:"The W3C Document Object Model (DOM) is a platform

and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."

The W3C DOM standard is separated into 3 different parts:

Core DOM - standard model for all document typesXML DOM - standard model for XML documentsHTML DOM - standard model for HTML documents

Page 37: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

What is the HTML DOM?

37

The HTML DOM is a standard object model and programming interface for HTML. It defines:

The HTML elements as objectsThe properties of all HTML elementsThe methods to access all HTML elementsThe events for all HTML elementsIn other words: The HTML DOM is a

standard for how to get, change, add, or delete HTML elements.

Page 38: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

38

In the HTML DOM object model, the document object represents your web page.

Dom API is implemented by different browser vendors.

The document object is the owner of all other objects in your web page.

If you want to access objects in an HTML page, you always start with accessing the document object.

Page 39: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

39

Representation of DOM tree in browser

Page 40: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Real power of javascript

40

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

JavaScript can change all the HTML elements in the page

JavaScript can change all the CSS styles in the page

JavaScript can remove existing HTML elements and attributes

JavaScript can react to all existing HTML events in the page

Page 41: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

JavaScript - HTML DOM Methods

41

HTML DOM methods are actions you can perform (on HTML Elements)

HTML DOM properties are values (of HTML Elements) that you can set or change

Page 42: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

The DOM Programming Interface

42

The HTML DOM can be accessed with JavaScript (and with other programming languages).

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.

Page 43: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Manipulating contents

43

The getElementById MethodThe most common way to access an HTML

element is to use the id of the element.In the example above the getElementById

method used id="demo" to find the element.The innerHTML PropertyThe easiest way to get the content of an

element is by using the innerHTML property.The innerHTML property is useful for getting

or replacing the content of HTML elements.

Page 44: JavaScript is an object-based scripting language that is lightweight and cross-platform. 3-Feb-16 JavaScript.

Finding HTML Elements

44

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are a couple of ways to do this:

Finding HTML elements by idFinding HTML elements by tag nameFinding HTML elements by class nameFinding HTML elements by CSS selectorsFinding HTML elements by HTML object

collections