24
By: Sahil Goel

Java script

Embed Size (px)

DESCRIPTION

Anything and everything about #javaScript by Sahil Goel

Citation preview

Page 1: Java script

By: Sahil Goel

Page 2: Java script

WHAT IS JAVASCRIPT?

• JavaScript is a scripting language (a scripting language is a lightweight programming language)

• JavaScript was designed to add interactivity to HTML pages • JavaScript is an interpreted language (means that scripts execute without

preliminary compilation) • Everyone can use JavaScript without purchasing a license • JavaScript is used in millions of Web pages to improve the design, validate

forms, detect browsers, create cookies, and much more.• JavaScript works in all major browsers, such as Internet Explorer, Mozilla,

Firefox, Opera.

Page 3: Java script

Where did it come from

• Originally called LiveScript at Netscape started out to be a server side scripting language for providing database connectivity and dynamic HTML generation on Netscape Web Servers.

• Netscape decided it would be a good thing for their browsers and servers to speak the same language so it got included in Navigator.

• Netscape in alliance with Sun jointly announced the language and its new name Java Script

• Because of rapid acceptance by the web community Microsoft forced to include in IE Browser

Page 4: Java script

Are Java and JavaScript the Same?

• Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.

• It can be used to create standalone applications and a special type of mini application, called an applet.

• JavaScript (developed by Netscape), is a smaller language that does not create applets or standalone applications. In its most common form today, JavaScript resides inside HTML documents, and can provide levels of interactivity far beyond typically flat HTML pages

NO! Java and JavaScript are two completely different languages in both concept and design!

Page 5: Java script

How to Put a JavaScript Into an HTML Page?

We can add JavaScript in three ways in our document:1) Inline<input type="button" id="hello-world2" value="Hello" onClick="alert('Hello World!');" />

2) Embedded<script type="text/javascript">function helloWorld() { alert('Hello World!') ; } </script>

3) External <head> <script type="text/javascript" language="javascript" src="hello.js"></script></head>

Page 6: Java script

How to Put a JavaScript Into an HTML Page?

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

Ending Statements With a Semicolon? • With traditional programming

languages, like C++ and Java, each code statement has to end with a semicolon (;).

• Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line.

NOTE: At times JavaScript is disabled in some browsers and it becomes difficult to get appropriate behavior and the user get confused, so to avoid such conditions we should check if it is enable or we should display an appropriate message. We can do this with the help of:<noscript> <p>This will not be displayed if JavaScript is enabled</p> </noscript>

Page 7: Java script

JavaScript Terminology

Objects:• Almost everything in JavaScript

is an Object: String, Number, Array, Function....

• An object is just a special kind of data, with properties and methods.

• Objects have properties that act as modifiers.

Properties:• Properties are object attributes. • Object properties are defined by

using the object's name, a period, and the property name.

• e.g., background color is expressed by: document.bgcolor document is the object .bgcolor is the property.Eg: personObj=new Object();

personObj.firstname="John";personObj.lastname="Doe";personObj.age=50;personObj.eyecolor="blue";

Page 8: Java script

JavaScript Terminology

Methods:• Methods are actions applied to

particular objects. Methods are what objects can do.

e.g.,document.write(”Hello World")document is the object.write is the method.

Events:• Events associate an object with

an action. e.g., the onclick event handler action can change an image.e.g., the onSubmit event handler sends a form. • User actions trigger events.

Page 9: Java script

JavaScript Terminology

Functions:• Functions are named statements

that performs tasks. e.g. function doWhatever()

{ statement here}

The curly braces contain the statements of the function.• JavaScript has built-in functions,

and we can write our own.

Values:• Values are bits of information. • Values, types and some examples

include:Number: 1, 2, 3, etc.String: characters enclosed in quotes. Boolean: true or false. Object: image, formFunction: validate, doWhatever

Page 10: Java script

JavaScript TerminologyVariables:• Variables contain values and use

the equal sign to specify their value.

• Variables are created by declaration using the var command with or without an initial value state.

e.g. var month;e.g. var month = April;

Expressions :• Expressions are commands that

assign values to variables. • Expressions always use an

assignment operator, such as the equals sign.

e.g., var month = May; is an expression. • Expressions end with a

semicolon.

Page 11: Java script

JavaScript TerminologyOperators:• Operators are used to handle variables. Types of operators with examples:Arithmetic operators, such as plus(+).Comparisons operators, such as equals(==).Logical operators, such as AND.Assignment like (=).+ Operator: The + operator can also be used to add string variables or text values together.

Page 12: Java script

Condition statements• Very often when we write code, we want to perform different actions

for different decisions. we can use conditional statements in our code to do this.

In JavaScript we have the following conditional statements:• if statement - use this statement if we want to execute some code only

if a specified condition is true • if...else statement - use this statement if we want to execute some

code if the condition is true and another code if the condition is false • if...else if....else statement - use this statement if we want to select one

of many blocks of code to be executed • switch statement - use this statement if we want to select one of many

blocks of code to be executed

Page 13: Java script

LoopsJavaScript performs several types of repetitive operations, called "looping".• for loop: The for loop is executed till a specified condition returns falsefor (initialization; condition; increment) { // statements}• while loop: The while statement repeats a loop as long as a specified

condition evaluates to true.while (condition) { // statements}

Page 14: Java script

Arrays

Creating arrays:• var badArray = new

Array(10); // Creates an empty Array that's sized for 10 elements.

• var goodArray= [10]; //Creates an Array with 10 as the first element.

Initializing an array:• Var myArray= new Array(“January”,” February”,”

March”);• var myArray = ['January', 'February', 'March'];

document.write(myArray[0]);//output: January document.write(myArray[1]);//output: February document.write(myArray[2]);//output: March

Arrays are usually a group of the same variable type that use an index number to distinguish them from each other. Arrays are one way of keeping a program more organized.

Page 15: Java script

JavaScript Popup Boxes

It is possible to make three different kinds of popup boxes:1) Alert Box• An alert box is often used if we want to make sure information comes

through to the user.• When an alert box pops up, the user will have to click "OK" to proceed.

<script>alert("Hello World")</script>

Page 16: Java script

2) Confirm Box • A confirm box is often used if we want the user to verify or accept

something.• When a confirm box pops up, the user will have to click either "OK" or

"Cancel" to proceed. • If the user clicks "OK", the box returns true. If the user clicks "Cancel",

the box returns false.

<script>var r=confirm("Press a button!");if (r==true) document.write("You pressed OK!“); elsedocument.write("You pressed Cancel!“);</script>

Page 17: Java script

3) Prompt Box• A prompt box is often used if you want the user to input a value before

entering a page.• When a prompt box pops up, the user will have to click either "OK" or

"Cancel" to proceed after entering an input value. • If the user clicks "OK“, the box returns the input value. If the user clicks

"Cancel“, the box returns null.

<script>x=prompt (“Please enter your name”, “sahil goel ”)document.write(“Welcome <br>”+x)</script>

Page 18: Java script

DOM• The Document Object Model (DOM) is the model that describes how all

elements in an HTML page, like input fields, images, paragraphs etc., are related to the topmost structure: the document itself. By calling the element by its proper DOM name, we can influence it.

• In DOM each object, whatever it may be exactly, is a Node.Node object: We can traverse through different nodes with the help of certain node properties and methods:Eg: firstChild, lastChild, parentNode, nextSibling, previousSibling etc.Document object:The Document object gives us access to the document's data. Some document methods are:Eg: getElementById(), getElementsByTagName() etc.

Page 19: Java script

What is a Cookie?A cookie is a small text file that JavaScript can use to store information about a user.• There are two types of cookies:

– 1) Session Cookies – 2) Persistent Cookies

Session Cookies :A browser stores session cookies in memory. • Once a browser session ends, browser loses the contents of a session cookie.

–Persistent Cookies: Browsers store persistent cookies to a user’s hard drive.• We can use persistent cookies to get information about a user that we can use

when the user returns to a website at a later date.

Page 20: Java script

More about Cookies• JavaScript deals with cookies as objects. • JavaScript works with cookies using the document.cookie

attribute.

Examples of cookie usage:• User preferences• Saving form data• Tracking online shopping habits

Page 21: Java script

Parts of a Cookie Object• name – An identifier by which we reference a particular cookie.• value – The information we wish to save, in reference to a particular

cookie.• expires – A GMT-formatted date specifying the date (in milliseconds)

when a cookie will expire.• path – Specifies the path of the web server in which the cookie is

valid. By default, set to the path of the page that set the cookie. However, commonly specified to /, the root directory.

• domain – Specifies the domain for which the cookie is valid. Set, by default, only to the full domain of a page..

• secure – Specifies that a web browser needs a secure HTTP connection to access a cookie.

Page 22: Java script

Setting a Cookie – General Form:

document.cookie = “cookieName = cookieValue; expires = expireDate; path = pathName; domain = domainName; secure”;

Escape Sequences:• When we set cookie values, we must first convert the string values that

set a cookie so that the string doesn’t contain white space, commas or semi-colons.

• We can use JavaScript’s intrinsic escape() function to convert white space and punctuation with escape sequences.

• Conversely, we can use unescape() to view text encoded with escape().

Page 23: Java script

Cookie limitations:

• A given domain may only set 20 cookies per machine.• A single browser may only store 300 cookies.• Browsers limit a single cookie to 4KB.

Page 24: Java script

THANK YOU!