java script ppt

44
Javascript Priya goyal

Upload: priya-goyal

Post on 20-Jan-2017

306 views

Category:

Engineering


0 download

TRANSCRIPT

Page 1: Java Script ppt

JavascriptPriya goyal

Page 2: Java Script ppt

What is JavaScript

JavaScript ("JS" for short) is a full-fledged dynamic programming language that, when applied to an HTML document, can provide dynamic interactivity on websites.

It was invented by Brendan Eich, co-founder of the Mozilla project, the Mozilla Foundation, and the Mozilla Corporation.

We can do pretty much anything with JavaScript, such as image galleries, fluctuating layouts, and responses to button clicks. And if get more experienced with the language, we'll be able to create games, animated 2D and 3D graphics, full blown database-driven apps, and more!

Page 3: Java Script ppt

Advantages of JavaScript

Saving bandwidth and strain on the web server.Javascript is executed on the client side

Javascript is relatively fast to the end userJavascript is executed on the client side

Page 4: Java Script ppt

Limitations of JavaScript

Security IssuesJavascript snippets, once appended onto web pages execute on client servers immediately and therefore can also be used to exploit the user's system. While a certain restriction is set by modern web standards on browsers, malicious code can still be executed complying with the restrictions set.

Javascript rendering variesDifferent layout engines may render Javascript differently resulting in inconsistency in terms of functionality and interface. While the latest versions of javascript and rendering have been geared towards a universal standard, certain variations still exist.

Page 5: Java Script ppt

Client-side JavaScript

A scripting or script language is a programming language that supports scripts, programs written for a special run-time environment that automate the execution of tasks that could alternatively be executed one-by-one by a human operator. Scripting languages are often interpreted (rather than compiled).

Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side.

Client-side scripts do not require additional software on the server (making them popular with authors who lack administrative access to their servers); however, they do require that the user's web browser understands the scripting language in which they are written.

Client-side scripting is not inherently unsafe. Users, though, are encouraged to always keep their web browsers up-to-date to avoid exposing their computer and data to new vulnerabilities.

Page 6: Java Script ppt

Places to put JavaScript code

1. Between the body tag of html2. Between the head tag of html3. In .js file (external javaScript)

Page 7: Java Script ppt

Between the body tag

In the above example, we have displayed the dynamic content using JavaScript. Let’s see the simple example of JavaScript that displays alert dialog box.

<script type="text/javascript">   alert("Hello Javatpoint");  </script>  

Page 8: Java Script ppt

Internal Javascript

<html> <head>

<script>………JavaScript code………..</script>

</head><body>

</body> </html> We can place the <script> tags, containing your JavaScript,

anywhere within you web page, but it is normally recommended that we should keep it within the <head> tags.

Page 9: Java Script ppt

External JavaScript File

<html> <head> <script type="text/javascript" src="filename.js" > ………JavaScript code……….. </script> </head> <body> </body> </html>

function sayHello() { alert("Hello World") }

Test.html

Filename.js

Page 10: Java Script ppt

Case Sensitivity

JavaScript is a case-sensitive language.

Page 11: Java Script ppt

Comments

Single line comment// This is a comment

Multiline comment/* line 1line 2line 3 */

Page 12: Java Script ppt

Data Types

Variable Explanation Example

String A string of text. To signify that the variable is a string, you should enclose it in quote marks. var myVariable = 'Bob';

Number A number. Numbers don't have quotes around them. var myVariable = 10;

BooleanA True/False value. The words true and false are special keywords in JS, and don't need quotes.

var myVariable = true;

Array A structure that allows you to store multiple values in one single reference.

var myVariable = [1,'Bob','Steve',10];Refer to each member of the array like this:myVariable[0], myVariable[1], etc.

ObjectBasically, anything. Everything in JavaScript is an object, and can be stored in a variable. Keep this in mind as you learn.

var myVariable = document.querySelector('h1');All of the above examples too.

Page 13: Java Script ppt

Operators

What is an operator? Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called

operands and ‘+’ is called the operator. JavaScript supports the following types of operators.

Assignment operators Comparison operators Arithmetic operators Bitwise operators Bitwise shift operators Logical operators Conditional (ternary) operator

Page 14: Java Script ppt

Operator precedenceOperator type Individual operatorsmember . []call / create instance () newnegation/increment ! ~ - + ++ -- typeof void deletemultiply/divide * / %addition/subtraction + -bitwise shift << >> >>>relational < <= > >= in instanceofequality == != === !==bitwise-and &bitwise-xor ^bitwise-or |logical-and &&logical-or ||conditional ?:assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=comma ,

Page 15: Java Script ppt

JavaScript Array

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

There are 3 ways to construct array in JavaScript1. By array literal2. By creating instance of Array directly (using new keyword)3. By using an Array constructor (using new keyword)

Page 16: Java Script ppt

1) JavaScript array literal

The 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.<script>  var emp=["Sonoo","Vimal","Ratan"];  for (i=0;i<emp.length;i++){  document.write(emp[i] + "<br/>");  }  </script>  

Page 17: Java Script ppt

2) JavaScript Array directly (new keyword) The syntax of creating array directly is given below:

var arrayname=new Array();   Here, new keyword is used to create instance of array. Let’s see the example of creating array directly.

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

Page 18: Java Script ppt

3) JavaScript array constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that we don't have to provide value explicitly.var arrayname=new Array(value1,value2.....valueN);  

The example of creating object by array constructor is given below.

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

Page 19: Java Script ppt

How to access an array

Access the Elements of an ArrayYou refer to an array element by referring to the index number.cars[0] = "Opel"; var cars = ["Saab", "Volvo", "BMW"];document.getElementById("demo").innerHTML = cars[0];

Access the Full ArrayWith JavaScript, the full array can be accessed by referring to the array name:var cars = ["Saab", "Volvo", "BMW"];document.getElementById("demo").innerHTML = cars;

Page 20: Java Script ppt

Arrays are objects

Arrays are a special type of objects. var person = ["John", "Doe", 46];

Objects use names to access its "members". In this example, person.firstName returns John:

var person = {firstName:"John", lastName:"Doe", age:46}; Document.write(person.firstname);

Page 21: Java Script ppt

Array Methods concat()

Javascript array concat() method returns a new array comprised of this array joined with two or more arrays.array.concat(value1, value2, ..., valueN);

indexOf()Javascript array indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.array.indexOf(searchElement[, fromIndex]);LastIndexOf()Javascript array lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.array.lastIndexOf(searchElement[, fromIndex]);Join()Javascript array join() method joins all the elements of an array into a string.array.join(separator);sort()Javascript array sort() method sorts elements of an array.array.sort(function);

Page 22: Java Script ppt

Array Methods Push()

Javascript array pop() method insert an element at the end of an array Array.push(value);

Pop()Javascript array pop() method removes the last element from an array and returns that element.Array.pop(value);Reverse()Javascript array reverse() mmethod reverses the element of an array. The first array element becomes the last and the last becomes the first.Array.Reverse();Unshift()Adds one or more elements to the front of an array and returns the new length of the array.Array.Unshift(value);Shift()Javascript array shift()method removes the first element from an array and returns that element.Array.Shift();

Page 23: Java Script ppt

Array Methods splice()

The splice() method adds/removes items to/from an array, and returns the removed item(s).array.splice(index,howmany,item1,.....,itemX)

 slice()The slice() method returns the selected elements in an array, as a new array object.array.slice(start,end)

index Required. specifies at what position to add/remove items

howmany Required. The number of items to be removeditem1, ..., itemX Optional. The new item(s) to be added to the array

start Optional. specifies where to start the selection (count starts from index value 0).

end Optional. specifies where to end the selection. (count starts from 1).

Page 24: Java Script ppt

JavaScript String The JavaScript string is an object that represents a sequence of characters. There are 2 ways to create string in JavaScript By string literal

var stringname="string value";   By string object (using new keyword)

var stringname=new String("string literal");  

Page 25: Java Script ppt

JavaScript String Methods charAt(index)

The JavaScript String charAt() method returns the character at the given index.document.write(str.charAt(2));  

concat(str)The JavaScript String concat(str) method concatenates or joins two strings.var s1="javascript ";  var s2="concat example";  var s3=s1.concat(s2);  

indexOf(str)The JavaScript String indexOf(str) method returns the index position of the given string.var s1="javascript from javatpoint indexof";  var n=s1.indexOf("from");  

lastIndexOf(str)The JavaScript String lastIndexOf(str) method returns the last index position of the given string.var s1="javascript from javatpoint indexof";  var n=s1.lastIndexOf("java");  

Page 26: Java Script ppt

JavaScript String Methods toLowerCase()

This method returns the given string in lowercase letters.var s1="JavaScript toLowerCase Example";  var s2=s1.toLowerCase();  

toUpperCase()This method returns the given string in Uppercase letters.var s1="JavaScript toUpperCase Example";  var s2=s1.toUpperCase();  

slice(beginIndex, count)This method returns the parts of string from given beginIndex to count. In slice() method, beginIndex is inclusive and count is exclusive. (beginIndex starts from 0th element of array and count starts from beginIndex)var s2=s1.slice(2,5);  

trim()This method removes leading and trailing whitespaces from the string.var s1="     javascript trim    ";  var s2=s1.trim();  

Page 27: Java Script ppt

Javascript DOM

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.window.document  Is same as document  

Page 28: Java Script ppt

Methods Document Object

Method Description Exampledocument.write("string") writes the given string on the doucment. document.write(‘’hello”);

document.writeln("string") writes the given string on the doucment with newline character at the end.

document.write(‘’hello”);

document.getElementById() returns the element having the given id value. var a=document.getElementById(“p1”).value

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

var a=document.getElementsByName(“pera”).value

document.getElementsByTagName()

returns all the elements having the given tag name.

var a=document.getElementsByTagName(“p”).value

document.getElementsByClassName()

returns all the elements having the given class name.

var a=document.getElementsByClassName(“class1”).value

document.querySelector() Returns the first element that matches a specified CSS selector(s) in the document

Var a = document.querySelector(“.classname”);

Page 29: Java Script ppt

Methods Document Object

Example:<body>

<p class=“class1” name=“pera”>demo1</p><p class=“class1” name=“pera”>demo2</p><p id="p1“ ></p><script>

var x = document.getElementsByTagName("p"); //put ClassName or Name in the place of TagName

document.getElementById("p1").innerHTML =x[0].innerHTML;</script>

</body>

Output:

demo1demo2demo3

Page 30: Java Script ppt

Methods Document ObjectMethod Descriptiondocument.title Sets or returns the title of the document

document.URL Returns the full URL of the HTML document

document.cookie Returns all name/value pairs of cookies in the document

document.createAttribute() Creates an attribute node

document.body Sets or returns the document's body (the <body> element)

document.form() Returns the elements value/name of form

<form id="myForm" name="myForm"><input id="email" name="email" value="[email protected]" />

</form><script>

document.forms["myForm"]["email"].value</script>

Page 31: Java Script ppt

Adding and Deleting HTML ElementsMethod Descriptiondocument.createElement(element) Create an HTML elementdocument.removeChild(element) Remove an HTML elementdocument.appendChild(element) Add an HTML elementdocument.replaceChild(element) Replace an HTML element

<body><div id="d1">

hello</div><script>

var x = document.createElement('span');x.innerHTML = "Hello!";//document.body.appendChild(x); //append in bodydocument.getElementById("d1").appendChild(x); //append in particular element

</script></body>

Page 32: Java Script ppt

Methods Element Object

Method Description Exampleelement.style.property Sets or returns the value of the style attribute of

an elementdocument.getElementById(“p1”).style.color=“red”;

element.tagName Returns the tag name of an element Var x=document.getElementById(“p1”).tagName

element.innerHTML Sets or returns the content of an element p.innerHtml=“hello’;

element.id Sets or returns the value of the id attribute of an element

Var x=document.getElementsByTagName(“p”).id

element.attribute Change the attribute value of an HTML element <img src=“1.jpg”></img><script>document.getElementById(“img1”).src=“2.jpg”</script>

element.setAttribute(attribute, value)

Change the attribute value of an HTML element Ex1: document.getElementsByTagName("H1")[0].setAttribute("class", “newclass");

Ex2: element.setAttribute("style", "background-color: red;");

Page 33: Java Script ppt

Methods  DOM Attribute Object

Method Description Exampleattr.name Returns the name of an attribute var

a=document.getElementById(“p1”).name

attr.value Sets or returns the value of the attribute

var a=document.getElementById(“txt1”).value

•  innerText retrieves and sets the content of the tag as plain text, whereas innerHTML retrieves and sets the same content but in HTML format.

innerText Vs innerHTML

Page 34: Java Script ppt

Browser Object model

Page 35: Java Script ppt

JavaScript Popup Boxes It is possible to make three different kinds of popup windows Alert Box

An alert box is often used if you 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.

alert("sometext");

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

Page 36: Java Script ppt

JavaScript Popup Boxes - 2 Confirm Box

A confirm box is often used if you 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.

confirm("sometext");<script>function myFunction() { var x; if (confirm("Press a button!") == true) { x = "You pressed OK!"; } else { x = "You pressed Cancel!"; } document.getElementById("demo").innerHTML = x;}</script>

Page 37: Java Script ppt

JavaScript Popup Boxes - 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.prompt("sometext","defaultText");

Hello Alice! How are you today?

<script>function myFunction() { var person = prompt("Please enter your name"); if (person != null) { document.getElementById("demo").innerHTML = "Hello " + person + "! How are you today?"; }}</script>

Page 38: Java Script ppt

Timing EventssetTimeout() Method

setTimeout(function, milliseconds)Executes a function, after waiting a specified number of milliseconds.

setInterval() Method

Var id_of_setinterval=setInterval(function, milliseconds)Same as setTimeout(), but repeats the execution of the function continuously.

clearInterval() Method

The clearInterval() method stops the executions of the function specified in the setInterval() method. It ret

clearInterval(id_of_setinterval)

* There are 1000 milliseconds in one second.

Page 39: Java Script ppt

Window Historyloads the URL in the history list.

history.back() - same as clicking back in the browserhistory.forward() - same as clicking forward in the browser

<head> <script> function goBack() {    window.history.back() }

function goForward() { window.history.forward() }</script>

</head><body> <input type="button" value="Back" onclick="goBack()"> <input type="button" value="Forward" onclick="goForward()"></body>

Page 40: Java Script ppt

Navigator object

Property Descriptionnavigator.appName returns the namenavigator.appVersion returns the versionnavigator.appCodeName returns the code namenavigator.cookieEnabled returns true if cookie is enabled otherwise falsenavigator.userAgent returns the user agentnavigator.language returns the language. It is supported in Netscape and Firefox only.navigator.userLanguage returns the user language. It is supported in IE only.navigator.plugins returns the plugins. It is supported in Netscape and Firefox only.navigator.systemLanguage returns the system language. It is supported in IE only.navigator.mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox only.navigator.platform returns the platform e.g. Win32.navigator.online returns true if browser is online otherwise false.

The JavaScript navigator object is used for browser detection. It can be used to get browser information. There are many properties of navigator object that returns information of the browser.

Page 41: Java Script ppt

Window Screen

Property Descriptionscreen.width returns the width of the visitor's screen

screen.height returns the height of the visitor's screen

screen.availWidth returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.

screen.availHeight returns the height of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.

screen.colorDepth returns the number of bits used to display one color.

screen.pixelDepth returns the pixel depth of the screen.

It contains information about the user's screen.

Page 42: Java Script ppt

HTML/DOM events for JavaScriptEvents Descriptiononclick occurs when element is clicked.ondblclick occurs when element is double-clicked.

onfocus occurs when an element gets focus such as button, input, textarea etc.

onblur occurs when form looses the focus from an element.onsubmit occurs when form is submitted.onmouseover occurs when mouse is moved over an element.

onmouseout occurs when mouse is moved out from an element (after moved over).

onmousedown occurs when mouse button is pressed over an element.

onmouseup occurs when mouse is released from an element (after mouse is pressed).

onload occurs when document, object or frameset is loaded.onunload occurs when body or frameset is unloaded.onscroll occurs when document is scrolled.onresized occurs when document is resized.onreset occurs when form is reset.onkeydown occurs when key is being pressed.onkeypress occurs when user presses the key.onkeyup occurs when key is released.

Page 43: Java Script ppt

References

http://www.javatpoint.com/javascript-tutorial http://www.w3schools.com/js/default.asp https://developer.mozilla.org

Page 44: Java Script ppt

Thank you