SlideShare une entreprise Scribd logo
1  sur  44
Javascript
Priya goyal
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!
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 user
Javascript is executed on the client side
Limitations of JavaScript
 Security Issues
Javascript 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 varies
Different 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.
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.
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)
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>  
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.
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
Case Sensitivity
 JavaScript is a case-sensitive language.
Comments
 Single line comment
// This is a comment
 Multiline comment
/* line 1
line 2
line 3 */
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;
Boolean
A 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.
Object
Basically, 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.
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
Operator precedence
Operator type Individual operators
member . []
call / create instance () new
negation/increment ! ~ - + ++ -- typeof void delete
multiply/divide * / %
addition/subtraction + -
bitwise shift << >> >>>
relational < <= > >= in instanceof
equality == != === !==
bitwise-and &
bitwise-xor ^
bitwise-or |
logical-and &&
logical-or ||
conditional ?:
assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=
comma ,
JavaScript Array
 JavaScript 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)
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>  
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>  
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>  
How to access an array
 Access the Elements of an Array
You 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 Array
With JavaScript, the full array can be accessed by referring to the array name:
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
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);
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);
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();
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 removed
item1, ..., 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).
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");
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");  
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();  
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  
Methods Document Object
Method Description Example
document.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.getElementsByClassNam
e()
returns all the elements having the given class
name.
var
a=document.getElementsByClassName(“class1”).val
ue
document.querySelector() Returns the first element that matches a specified
CSS selector(s) in the document
Var a = document.querySelector(“.classname”);
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:
demo1
demo2
demo3
Methods Document Object
Method Description
document.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="some@email.com" />
</form>
<script>
document.forms["myForm"]["email"].value
</script>
Adding and Deleting HTML Elements
Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.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 body
document.getElementById("d1").appendChild(x); //append in particular element
</script>
</body>
Methods Element Object
Method Description Example
element.style.property Sets or returns the value of the style attribute of an
element
document.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;");
Methods DOM Attribute Object
Method Description Example
attr.name Returns the name of an attribute var
a=document.getElementById(“p1”).nam
e
attr.value Sets or returns the value of the
attribute
var
a=document.getElementById(“txt1”).valu
e
•  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
Browser Object model
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>
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>
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>
Timing Events
setTimeout() 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.
Window History
loads the URL in the history list.
history.back() - same as clicking back in the browser
history.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>
Navigator object
Property Description
navigator.appName returns the name
navigator.appVersion returns the version
navigator.appCodeName returns the code name
navigator.cookieEnabled returns true if cookie is enabled otherwise false
navigator.userAgent returns the user agent
navigator.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.
Window Screen
Property Description
screen.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.
HTML/DOM events for JavaScript
Events Description
onclick 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.
References
 http://www.javatpoint.com/javascript-tutorial
 http://www.w3schools.com/js/default.asp
 https://developer.mozilla.org
Thank you

Contenu connexe

Tendances (20)

Javascript
JavascriptJavascript
Javascript
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Js ppt
Js pptJs ppt
Js ppt
 
CSS
CSSCSS
CSS
 
An Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java ScriptAn Overview of HTML, CSS & Java Script
An Overview of HTML, CSS & Java Script
 
Java script
Java scriptJava script
Java script
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Introduction to JavaScript (1).ppt
Introduction to JavaScript (1).pptIntroduction to JavaScript (1).ppt
Introduction to JavaScript (1).ppt
 
Java script
Java scriptJava script
Java script
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Java script ppt
Java script pptJava script ppt
Java script ppt
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 

En vedette

Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy stepsprince Loffar
 
Javascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to TitaniumJavascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to TitaniumTechday7
 
Basics of Computer graphics lab
Basics of Computer graphics labBasics of Computer graphics lab
Basics of Computer graphics labPriya Goyal
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 

En vedette (8)

basics of css
basics of cssbasics of css
basics of css
 
Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
Jsp
JspJsp
Jsp
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
Javascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to TitaniumJavascript Best Practices and Intro to Titanium
Javascript Best Practices and Intro to Titanium
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Basics of Computer graphics lab
Basics of Computer graphics labBasics of Computer graphics lab
Basics of Computer graphics lab
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 

Similaire à Java Script ppt (20)

Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
Java script basics
Java script basicsJava script basics
Java script basics
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
CSC PPT 12.pptx
CSC PPT 12.pptxCSC PPT 12.pptx
CSC PPT 12.pptx
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentals
 
Javascript
JavascriptJavascript
Javascript
 
Java script
 Java script Java script
Java script
 
js.pptx
js.pptxjs.pptx
js.pptx
 
Java script
Java scriptJava script
Java script
 
ABCs of Programming_eBook Contents
ABCs of Programming_eBook ContentsABCs of Programming_eBook Contents
ABCs of Programming_eBook Contents
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]Vb script tutorial for qtp[1]
Vb script tutorial for qtp[1]
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
Javascript
JavascriptJavascript
Javascript
 
Unit 2.4
Unit 2.4Unit 2.4
Unit 2.4
 

Dernier

Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxRomil Mishra
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Crystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxCrystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxachiever3003
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate productionChinnuNinan
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentBharaniDharan195623
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating SystemRashmi Bhat
 
BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxNiranjanYadav41
 

Dernier (20)

Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Designing pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptxDesigning pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptx
 
Mine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptxMine Environment II Lab_MI10448MI__________.pptx
Mine Environment II Lab_MI10448MI__________.pptx
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Crystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxCrystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptx
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate production
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Configuration of IoT devices - Systems managament
Configuration of IoT devices - Systems managamentConfiguration of IoT devices - Systems managament
Configuration of IoT devices - Systems managament
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Main Memory Management in Operating System
Main Memory Management in Operating SystemMain Memory Management in Operating System
Main Memory Management in Operating System
 
BSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptxBSNL Internship Training presentation.pptx
BSNL Internship Training presentation.pptx
 

Java Script ppt

  • 2. 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!
  • 3. 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 user Javascript is executed on the client side
  • 4. Limitations of JavaScript  Security Issues Javascript 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 varies Different 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.
  • 5. 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.
  • 6. 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)
  • 7. 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>  
  • 8. 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.
  • 9. 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
  • 10. Case Sensitivity  JavaScript is a case-sensitive language.
  • 11. Comments  Single line comment // This is a comment  Multiline comment /* line 1 line 2 line 3 */
  • 12. 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; Boolean A 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. Object Basically, 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.
  • 13. 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
  • 14. Operator precedence Operator type Individual operators member . [] call / create instance () new negation/increment ! ~ - + ++ -- typeof void delete multiply/divide * / % addition/subtraction + - bitwise shift << >> >>> relational < <= > >= in instanceof equality == != === !== bitwise-and & bitwise-xor ^ bitwise-or | logical-and && logical-or || conditional ?: assignment = += -= *= /= %= <<= >>= >>>= &= ^= |= comma ,
  • 15. JavaScript Array  JavaScript 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)
  • 16. 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>  
  • 17. 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>  
  • 18. 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>  
  • 19. How to access an array  Access the Elements of an Array You 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 Array With JavaScript, the full array can be accessed by referring to the array name: var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars;
  • 20. 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);
  • 21. 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);
  • 22. 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();
  • 23. 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 removed item1, ..., 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).
  • 24. 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");
  • 25. 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");  
  • 26. 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();  
  • 27. 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  
  • 28. Methods Document Object Method Description Example document.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.getElementsByClassNam e() returns all the elements having the given class name. var a=document.getElementsByClassName(“class1”).val ue document.querySelector() Returns the first element that matches a specified CSS selector(s) in the document Var a = document.querySelector(“.classname”);
  • 29. 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: demo1 demo2 demo3
  • 30. Methods Document Object Method Description document.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="some@email.com" /> </form> <script> document.forms["myForm"]["email"].value </script>
  • 31. Adding and Deleting HTML Elements Method Description document.createElement(element) Create an HTML element document.removeChild(element) Remove an HTML element document.appendChild(element) Add an HTML element document.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 body document.getElementById("d1").appendChild(x); //append in particular element </script> </body>
  • 32. Methods Element Object Method Description Example element.style.property Sets or returns the value of the style attribute of an element document.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;");
  • 33. Methods DOM Attribute Object Method Description Example attr.name Returns the name of an attribute var a=document.getElementById(“p1”).nam e attr.value Sets or returns the value of the attribute var a=document.getElementById(“txt1”).valu e •  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
  • 35. 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>
  • 36. 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>
  • 37. 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>
  • 38. Timing Events setTimeout() 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.
  • 39. Window History loads the URL in the history list. history.back() - same as clicking back in the browser history.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>
  • 40. Navigator object Property Description navigator.appName returns the name navigator.appVersion returns the version navigator.appCodeName returns the code name navigator.cookieEnabled returns true if cookie is enabled otherwise false navigator.userAgent returns the user agent navigator.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.
  • 41. Window Screen Property Description screen.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.
  • 42. HTML/DOM events for JavaScript Events Description onclick 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.