SlideShare a Scribd company logo
Definition
• JavaScript is a loosely-typed client side scripting language that
executes in the user's browser.
• It interact with html elements in order to make interactive web user
interface.
• It allows the user to perform calculations, check forms, write
interactive games, add special effects, customize graphics selections,
create security passwords and more.
• It can be used in various activities like data validation, display popup
messages, handling different events , etc,.
Advantages of JavaScript:
• It executes on client's browser, so eliminates server side processing.
• It executes on any OS.
• JavaScript can be used with any type of web page e.g. PHP, ASP.NET,
Perl etc.
• Performance of web page increases due to client side execution.
• JavaScript code can be minified to decrease loading time from server.
JavaScript Overview
• Character Set: It uses the Unicode character set and so allows almost all
characters, punctuations, and symbols.
• Case Sensitive: It is a case sensitive scripting language. It means functions,
variables and keywords are case sensitive.
• String: String is a text in JavaScript. A text content must be enclosed in double
or single quotation marks.
• Number: It allows you to work with any kind of numbers like integer, float,
hexadecimal etc. Number must NOT be wrapped in quotation marks.
• Semicolon : It is Separated by a semicolon. However, it is not mandatory to end
every statement with a semicolon but it is recommended.
• White space: JavaScript ignores multiple spaces and tabs
JavaScript in HTML
• JavaScript code must be inserted between <script> and </script> tags.
• The script tag identifies a block of script code in the html page.
• It also loads a script file with src attribute.
• Scripts can be placed in the <body>, or in the <head> section of an HTML
page, or in both.
Example:
<script>
//Javascript codes..
</script>
External Script file
• External scripts are also used when the same code is used in many
different web pages.
• JavaScript files have the file extension .js.
• Advantages:
• It separates HTML and code
• Cached JavaScript files can speed up page loads
<script src="/PathToScriptFile.js"></<script>
<body>
<script src="myScript.js"></script>
</body>
function myFunction() {
document.getElementById("demo").innerHTML =
"Paragraph changed.";
}
myScript.js
HTML File
Example :
JavaScript Display
•Writing into an alert box, using window.alert().
•Writing into the HTML output using document.write().
•Writing into an HTML element, using innerHTML.
•The id attribute defines the HTML element.
• The innerHTML property defines the HTML content
•Writing into the browser console, using console.log().
•Activate the browser console with F12, and select "Console" in the menu.
<script>
window.alert(4 + 6);
</script>
<script>
document.write(1 + 6);
</script>
<script>
document.getElementById("demo").innerHTML =5 + 6;
</script>
<script>
console.log(5 + 6);
</script>
(For testing purposes)
JavaScript Operators and DataTypes:
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Assignment Operators
• Conditional Operators
Primitive Data Types:
1.String
2.Number
3.Boolean
4.Null
5.Undefined
Non-primitive Data Type:
1.Object
2.Date
3.Array
Operators
• typeof Operator:
• The typeof operator is a unary operator that is placed before its single operand,
which can be of any type.
• It evaluates to "number", "string", or "Boolean" if its operand is a number, string,
or Boolean value and returns true or false based on the evaluation.
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
Example:
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
var a = 10;
var b = "String";
Result => B is String
Result => A is Numeric
STRING
• String value can be assigned to a variable using equal to (=) operator.
• It must be enclosed in single or double quotation marks.
• It can be concatenated using plus (+) operator in JavaScript.
• A string can also be treated like zero index based character array.
• JavaScript also provides you String object to create a string
using new keyword.
var str1 = "Hello World";
var str2 = 'Hello World';
var str = 'We ' + "All" + 'Are ' + 'Alligators';
var str = 'Hello World';
str[0] // H
str[1] // e
str[2] // l
str.length // 11
var str1 = new String();
str1 = 'Hello World';
// It returns String object instead of string primitive.
Primitive Data Types
Null:
• data type of null is an object.
• null is "nothing".
• It is supposed to be something that doesn't exist. var person = null;
Undefined:
• JavaScript uninitialized variables value are undefined.
• Uninitialized variable (value undefined) equal to null.
• It uninitialized variables Boolean context return false
var str; // Declare variable without value. Identify as undefined value.
document.writeln(str == null); // Returns true
document.writeln(undefined == null); // Returns true
var bool = Boolean(str); // str is undefined passed into Boolean object
document.writeln(bool); // Boolean context Returns false
Non-Primitive Data Types
• Object:
• An object can be created in two ways:
• Object literal.
• Object constructor.
• Object Literal:
• The object literal is a simple way of creating an object using { } brackets.
• Use comma (,) to separate multiple key-value pairs.
• Example:
• var emptyObject = {}; // object with no properties or methods
• var person = { firstName: "John" }; // object with single property
Only property or method name without value is not valid.
var person = { firstName };  Wrong One
Non-Primitive Data Types
• Object Constructor:
• using new keyword.
• You can attach properties and methods using dot notation.
• Optionally, you can also create properties using [ ] brackets and specifying
property name as string.
Example:
var person = new Object();
// Attach properties and methods to person object
person.firstName = “Thalaivar";
person["lastName"] = “Felix";
person.age = 25;
person.getFullName = function ()
{ return this.firstName + ' ' + this.lastName;
};
// access properties & methods
person.firstName; // Thalaivar
person.lastName; // Felix
person.getFullName(); // Thalaivar Felix
var Alligator = new Object();
Aligator.firstName;
Consider this code alone:
 will return 'undefined' if you try to access properties
or call methods that do not exist.
Non-Primitive Data Types
• Date:
• provides Date object to work with date & time including days, months, years,
hours, minutes, seconds and milliseconds.
• Example:
var date1 = new Date("3 march 2015");
var date2 = new Date("3 February, 2015");
var date3 = new Date("3rd February, 2015");
var date4 = new Date("2015 3 February");
var date5 = new Date("3 2015 February ");
var date6 = new Date("February 3 2015");
var date7 = new Date("February 2015 3");
var date8 = new Date("3 2 2015");
Tue Mar 03 2015 00:00:00 GMT+0530 (India Standard Time)
Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time)
Invalid Date
Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time)
Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time)
Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time)
Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time)
Mon Mar 02 2015 00:00:00 GMT+0530 (India Standard Time)
Tue Mar 03 2015 20:21:44 GMT+0530 (India Standard Time)
Non-Primitive Data Types
Array:
An array is a special type of variable, which can store multiple values
using special syntax.
An array can be initialized using new keyword.
Example:
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var mixedArray = [1, "two", "three", 4];
var numericArray = new Array(2);
numericArray[0] = 1;
numericArray[1] = 2;
concat() Returns new array by combining values of an array that is specified as parameter with existing array values.
reverse() Reverses the elements of an array. Element at last index will be first and element at 0 index will be last.
shift() Removes the first element from an array and returns that element.
slice() Returns a new array with specified start to end elements.
some() Returns true if at least one element in this array satisfies the condition in the callback function.
sort() Sorts the elements of an array.
Methods:
DATATYPES EXAMPLE
var length = 16; // Number
var lastName = "Johnson"; // String
var cars = ["Saab", "Volvo", "BMW"]; // Array
var x = {firstName:"John", lastName:"Doe"}; // Object
var x = "Volvo" + 16 + 4;
Solve It :
var x = 16 + 4 + "Volvo" ;
JavaScript evaluates expressions from left to right.
Volvo164
164Volvo
FUNCTIONS
• defined using Function keyword and provides functions similar to
most of the scripting and programming languages.
• A function can have one or more parameters, which will be supplied
by the calling code and can be used inside a function.
• JavaScript is a dynamic type scripting language, so a function
parameter can have value of any data type.
• Functions can also be defined with a built-in JavaScript function
constructor called Function().
Example:
var x = function (a, b)
{return a * b};
 This is Function Constructor
var myFunction
= new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
FUNCTIONS
• Self-Invoking Functions:
• A self-invoking expression is invoked (started) automatically, without being
called.
• Function expressions will execute automatically if the expression is followed
by ().
• You cannot self-invoke a function declaration.
Example:
(function () {
var x = "Hello!!"; // invoke myself
})();
function myFunction(a, b) {
return a * b;
}
var txt = myFunction.toString();
toString() method returns the function as a string
FUNCTIONS WITH ARGUMENTS
function Alligator(firstName, lastName) {
alert("Hello " + firstName + " " + lastName); }
Alligator("Steve", "Jobs", "Mr.");
Alligator("Bill");
Alligator();
 display Hello Steve Jobs
 display Hello Bill undefined
 display Hello undefined undefined
 A function can have one or more parameters, which will be supplied by the calling code
and can be used inside a function.
 If you pass less arguments then rest of the parameters will be undefined.
 If you pass more arguments then additional arguments will be ignored.
 can return zero or one value using return keyword.
Example
Example :
function Sum(val1, val2) {
return val1 + val2;
};
CONTROL STRUCTURES
• IF CONDITION
• IF ELSE CONDITION
• ELSE IF CONDITION
• SWITCH CONDITION
• WHILE LOOP
• DO WHILE LOOP
• FOR LOOP
• FOR IN LOOP
• CONTINUE STATEMENT
• BREAK STATEMENT
Same Syntax and Same Format as in c#
for (x in person) {
text += person[x];
}
Example for in:
EXCEPTION HANDLING
SCOPE
• Scope in JavaScript defines accessibility of variables, objects and functions.
• There are two types of scope in JavaScript.
• Global scope
• Local scope
• Global scope:
• Variables declared outside of any function become global variables.
• Global variables can be accessed and modified from any function.
• Local scope:
• Variables declared inside any function with var keyword are called local variables.
• Local variables cannot be accessed or modified outside the function declaration.
var userName = "Bill";
function modifyUserName() {
userName = "Steve";
};
function createUserName() {
var userName = "Bill"; }
function showUserName() {
alert(userName);
}
createUserName();
showUserName(); // throws error
JavaScript Hoisting:
• a variable can be used before it has been declared.
• JavaScript only hoists declarations, not initializations.
• compiler moves all the declarations of variables and functions at the top so that there will
not be any error.
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
var x = 5; // Initialize x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = "x is " + x + " and y is " + y; // Display x and y
var y = 7; // Initialize y
Output:
5
Output:
x is 5 and y is undefined
JSON
• lightweight data interchange format.
• JSON data is written as name/value pairs.
• A name/value pair consists of a field name (in double quotes), followed by a
colon, followed by a value: "firstName":"John"
• JSON objects are written inside curly braces.
• JSON arrays are written inside square brackets.
• JSON data can be converted into JavaScript Objects using parse method.
JSON Example
-JavaScript Object Notation
{
"employees":[
{"firstName":“Gowtham", "lastName":“raj"},
{"firstName":“Felix", "lastName":“Nirmal"},
]
}
var obj = JSON.parse(text);
JAVASCRIPT HTML DOM
• Document Object Model
• When a web page is loaded, the browser creates Document Object Model of the page.
Define DOM ?
• The W3C DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
DOM Programming Interface:
• In the DOM, all HTML elements are defined as objects.
• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an HTML element).
• A method is an action you can do (like add or deleting an HTML element).
Example
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
getElementById is a method, while innerHTML is a property.
The getElementById Method
 The 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 Property
 The 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.
HTML DOM DOCUMENT OBJECTS
Methods Description
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class name
(represents your web page)
Method Description
element.innerHTML = new html
content
Change the inner HTML of an
element
element.attribute = new value Change the attribute value of an
HTML element
element.style.property = new style Change the style of an HTML element
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
document.write(text) Write into the HTML output stream
Finding HTML Elements
Adding Or Deleting
HTML Elements
Changing HTML
Elements
HTML DOM Elements
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections
var e = document.getElementById("intro");
var x = document.getElementsByTagName("p");
var x = document.getElementsByClassName("intro");
var x = document.querySelectorAll("p.intro");
var x = document.forms["frm1"];
var text = "";
var i;
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML = text;
GetElementByID() :
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
The document.getElementById() method
returns the element of specified id.
GetElementsByName() :
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total
Genders">
</form>
The document.getElementsByName() method
returns all the element of specified name.
GetElementsByTagName() :
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of
paragraphs by getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
The document.getElementsByTagName() method
returns all the element of specified tag name.
innerHTML property :
<script type="text/javascript" >
function showcommentform() {
var data="Name:<input type='text' name='name'><br>
Comment:<br><textarea rows='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
The innerHTML property can be used to write the
dynamic html on the html document.
innerTEXT property :
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
The innerText property can be used to write the
dynamic text on the html document.
JAVASCRIPT HTML DOM - Changing HTML
• The easiest way to modify the content of an HTML element is by using
the innerHTML property.
• Changing the Value of an Attribute :
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
<img id="myImage" src="smiley.gif">
<script>
document.getElementById("myImage").src = "landscape.jpg";
</script>
JAVASCRIPT HTML DOM - Changing CSS
• To change the style of an HTML element
• The HTML DOM allows you to execute code when an event occurs.
• Events are generated by the browser when :
• An element is clicked on
• The page has loaded
• Input fields are changed
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color = "blue";
</script>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.c
olor = 'red'">
Click Me!</button>
JAVASCRIPT HTML DOM Animation
• All animations should be relative to a container element.
• The container element should be created with style = "position: relative".
• The animation element should be created with style = "position: absolute".
<div id ="container">
<div id ="animate">My animation will go
here</div>
</div>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow; }
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;}
 JavaScript animations are done by programming gradual changes in an
element's style.
 The changes are called by a timer. When the timer interval is small, the
animation looks continuous
function myMove() {.getElementById("animate");
var pos = 0;
var id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + 'px';
elem.style.left = pos + 'px'; }}}
var elem = document
JAVASCRIPT HTML DOM EVENTS
Examples of HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
//INVOKES THE EVENTS
JAVASCRIPT HTML DOM EVENTS
• HTML Event Attributes: To assign events to HTML elements you can use event attributes.
• HTML DOM allows you to assign events to HTML elements using JavaScript.
• The onload and onunload Events
• The onload event can be used to check the visitor's browser type and browser version, and load
the proper version of the web page based on the information.
• The onchange event is often used in combination with validation of input fields.
<button onclick="displayDate()">Try it</button>
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
<body onload="checkCookies()">
<input type="text" id="fname" onchange="upperCase()"
JavaScript HTML DOM EVENTLISTENER
• The addEventListener() method
• The addEventListener() method attaches an event handler to the specified element.
• The addEventListener() method attaches an event handler to an element without
overwriting existing event handlers.
• The addEventListener() method allows you to add many events to the same element,
without overwriting existing events:
document.getElementById("myBtn").addEventListener("click", displayDate);
element.addEventListener("click", function(){ alert("Hello World!");});
//Add an Event Handler to an Element
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);

More Related Content

What's hot

Learning HTML
Learning HTMLLearning HTML
Learning HTML
Md. Sirajus Salayhin
 
Lecture 1 introduction to vb.net
Lecture 1   introduction to vb.netLecture 1   introduction to vb.net
Lecture 1 introduction to vb.net
MUKALU STEVEN
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
Neeru Mittal
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
Semi Detailed Lesson Plan in Programming Languages
Semi Detailed Lesson Plan in Programming LanguagesSemi Detailed Lesson Plan in Programming Languages
Semi Detailed Lesson Plan in Programming Languages
Manila Central University
 
Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)
AakankshaR
 
Programming Fundamentals lecture 1
Programming Fundamentals lecture 1Programming Fundamentals lecture 1
Programming Fundamentals lecture 1
REHAN IJAZ
 
HTML Text formatting tags
HTML Text formatting tagsHTML Text formatting tags
HTML Text formatting tags
Himanshu Pathak
 
Visual Basic IDE Introduction
Visual Basic IDE IntroductionVisual Basic IDE Introduction
Visual Basic IDE Introduction
Ahllen Javier
 
Html forms
Html formsHtml forms
Html forms
eShikshak
 
visual basic v6 introduction
visual basic v6 introductionvisual basic v6 introduction
visual basic v6 introduction
bloodyedge03
 
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
Fahim Abdullah
 
Php basics
Php basicsPhp basics
Php basics
Jamshid Hashimi
 
1. introduction to html5
1. introduction to html51. introduction to html5
1. introduction to html5
JayjZens
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
Rabin BK
 
Computer Hardware - Platforms and Technologies
Computer Hardware - Platforms and TechnologiesComputer Hardware - Platforms and Technologies
Computer Hardware - Platforms and Technologies
electricgeisha
 
Js ppt
Js pptJs ppt
Js ppt
Rakhi Thota
 
Lecture 1 intro to web designing
Lecture 1  intro to web designingLecture 1  intro to web designing
Lecture 1 intro to web designing
palhaftab
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
Rajat Saxena
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
Ameer Khan
 

What's hot (20)

Learning HTML
Learning HTMLLearning HTML
Learning HTML
 
Lecture 1 introduction to vb.net
Lecture 1   introduction to vb.netLecture 1   introduction to vb.net
Lecture 1 introduction to vb.net
 
Introduction to programming
Introduction to programmingIntroduction to programming
Introduction to programming
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Semi Detailed Lesson Plan in Programming Languages
Semi Detailed Lesson Plan in Programming LanguagesSemi Detailed Lesson Plan in Programming Languages
Semi Detailed Lesson Plan in Programming Languages
 
Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)Cascading Style Sheet (CSS)
Cascading Style Sheet (CSS)
 
Programming Fundamentals lecture 1
Programming Fundamentals lecture 1Programming Fundamentals lecture 1
Programming Fundamentals lecture 1
 
HTML Text formatting tags
HTML Text formatting tagsHTML Text formatting tags
HTML Text formatting tags
 
Visual Basic IDE Introduction
Visual Basic IDE IntroductionVisual Basic IDE Introduction
Visual Basic IDE Introduction
 
Html forms
Html formsHtml forms
Html forms
 
visual basic v6 introduction
visual basic v6 introductionvisual basic v6 introduction
visual basic v6 introduction
 
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
 
Php basics
Php basicsPhp basics
Php basics
 
1. introduction to html5
1. introduction to html51. introduction to html5
1. introduction to html5
 
Algorithm and flowchart
Algorithm and flowchartAlgorithm and flowchart
Algorithm and flowchart
 
Computer Hardware - Platforms and Technologies
Computer Hardware - Platforms and TechnologiesComputer Hardware - Platforms and Technologies
Computer Hardware - Platforms and Technologies
 
Js ppt
Js pptJs ppt
Js ppt
 
Lecture 1 intro to web designing
Lecture 1  intro to web designingLecture 1  intro to web designing
Lecture 1 intro to web designing
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 

Similar to Javascript

Java script
Java scriptJava script
Java script
Jay Patel
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
AlkanthiSomesh
 
Java script
Java scriptJava script
Java script
Abhishek Kesharwani
 
Javascript
JavascriptJavascript
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
rashmiisrani1
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptx
TusharTikia
 
Java script basics
Java script basicsJava script basics
Java script basics
Shrivardhan Limbkar
 
Java script
Java scriptJava script
Java script
vishal choudhary
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Marlon Jamera
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
Uchitha Bandara
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
Selvin Josy Bai Somu
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Java Script
Java ScriptJava Script
Java Script
Sarvan15
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
Html,javascript & css
Html,javascript & cssHtml,javascript & css
Html,javascript & css
Predhin Sapru
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
pkaviya
 
Javascript
JavascriptJavascript
Javascript
D V BHASKAR REDDY
 
Java script
Java scriptJava script
Java script
Sukrit Gupta
 

Similar to Javascript (20)

Java script
Java scriptJava script
Java script
 
Final Java-script.pptx
Final Java-script.pptxFinal Java-script.pptx
Final Java-script.pptx
 
Java script
Java scriptJava script
Java script
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript_III.pptx
JavaScript_III.pptxJavaScript_III.pptx
JavaScript_III.pptx
 
WT Unit-3 PPT.pptx
WT Unit-3 PPT.pptxWT Unit-3 PPT.pptx
WT Unit-3 PPT.pptx
 
Java script basics
Java script basicsJava script basics
Java script basics
 
Java script
Java scriptJava script
Java script
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
Client sidescripting javascript
Client sidescripting javascriptClient sidescripting javascript
Client sidescripting javascript
 
Javascript
JavascriptJavascript
Javascript
 
Java Script
Java ScriptJava Script
Java Script
 
Java Script
Java ScriptJava Script
Java Script
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Html,javascript & css
Html,javascript & cssHtml,javascript & css
Html,javascript & css
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
Javascript
JavascriptJavascript
Javascript
 
Java script
Java scriptJava script
Java script
 

Recently uploaded

KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
mamamaam477
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
abbyasa1014
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
Hitesh Mohapatra
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 

Recently uploaded (20)

KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
Engine Lubrication performance System.pdf
Engine Lubrication performance System.pdfEngine Lubrication performance System.pdf
Engine Lubrication performance System.pdf
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Engineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdfEngineering Drawings Lecture Detail Drawings 2014.pdf
Engineering Drawings Lecture Detail Drawings 2014.pdf
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
Generative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of contentGenerative AI leverages algorithms to create various forms of content
Generative AI leverages algorithms to create various forms of content
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 

Javascript

  • 1.
  • 2. Definition • JavaScript is a loosely-typed client side scripting language that executes in the user's browser. • It interact with html elements in order to make interactive web user interface. • It allows the user to perform calculations, check forms, write interactive games, add special effects, customize graphics selections, create security passwords and more. • It can be used in various activities like data validation, display popup messages, handling different events , etc,.
  • 3. Advantages of JavaScript: • It executes on client's browser, so eliminates server side processing. • It executes on any OS. • JavaScript can be used with any type of web page e.g. PHP, ASP.NET, Perl etc. • Performance of web page increases due to client side execution. • JavaScript code can be minified to decrease loading time from server.
  • 4. JavaScript Overview • Character Set: It uses the Unicode character set and so allows almost all characters, punctuations, and symbols. • Case Sensitive: It is a case sensitive scripting language. It means functions, variables and keywords are case sensitive. • String: String is a text in JavaScript. A text content must be enclosed in double or single quotation marks. • Number: It allows you to work with any kind of numbers like integer, float, hexadecimal etc. Number must NOT be wrapped in quotation marks. • Semicolon : It is Separated by a semicolon. However, it is not mandatory to end every statement with a semicolon but it is recommended. • White space: JavaScript ignores multiple spaces and tabs
  • 5. JavaScript in HTML • JavaScript code must be inserted between <script> and </script> tags. • The script tag identifies a block of script code in the html page. • It also loads a script file with src attribute. • Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both. Example: <script> //Javascript codes.. </script>
  • 6. External Script file • External scripts are also used when the same code is used in many different web pages. • JavaScript files have the file extension .js. • Advantages: • It separates HTML and code • Cached JavaScript files can speed up page loads <script src="/PathToScriptFile.js"></<script> <body> <script src="myScript.js"></script> </body> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } myScript.js HTML File Example :
  • 7. JavaScript Display •Writing into an alert box, using window.alert(). •Writing into the HTML output using document.write(). •Writing into an HTML element, using innerHTML. •The id attribute defines the HTML element. • The innerHTML property defines the HTML content •Writing into the browser console, using console.log(). •Activate the browser console with F12, and select "Console" in the menu. <script> window.alert(4 + 6); </script> <script> document.write(1 + 6); </script> <script> document.getElementById("demo").innerHTML =5 + 6; </script> <script> console.log(5 + 6); </script> (For testing purposes)
  • 8. JavaScript Operators and DataTypes: • Arithmetic Operators • Comparison Operators • Logical Operators • Assignment Operators • Conditional Operators Primitive Data Types: 1.String 2.Number 3.Boolean 4.Null 5.Undefined Non-primitive Data Type: 1.Object 2.Date 3.Array
  • 9. Operators • typeof Operator: • The typeof operator is a unary operator that is placed before its single operand, which can be of any type. • It evaluates to "number", "string", or "Boolean" if its operand is a number, string, or Boolean value and returns true or false based on the evaluation. result = (typeof b == "string" ? "B is String" : "B is Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); Example: result = (typeof a == "string" ? "A is String" : "A is Numeric"); document.write("Result => "); document.write(result); document.write(linebreak); var a = 10; var b = "String"; Result => B is String Result => A is Numeric
  • 10. STRING • String value can be assigned to a variable using equal to (=) operator. • It must be enclosed in single or double quotation marks. • It can be concatenated using plus (+) operator in JavaScript. • A string can also be treated like zero index based character array. • JavaScript also provides you String object to create a string using new keyword. var str1 = "Hello World"; var str2 = 'Hello World'; var str = 'We ' + "All" + 'Are ' + 'Alligators'; var str = 'Hello World'; str[0] // H str[1] // e str[2] // l str.length // 11 var str1 = new String(); str1 = 'Hello World'; // It returns String object instead of string primitive.
  • 11. Primitive Data Types Null: • data type of null is an object. • null is "nothing". • It is supposed to be something that doesn't exist. var person = null; Undefined: • JavaScript uninitialized variables value are undefined. • Uninitialized variable (value undefined) equal to null. • It uninitialized variables Boolean context return false var str; // Declare variable without value. Identify as undefined value. document.writeln(str == null); // Returns true document.writeln(undefined == null); // Returns true var bool = Boolean(str); // str is undefined passed into Boolean object document.writeln(bool); // Boolean context Returns false
  • 12. Non-Primitive Data Types • Object: • An object can be created in two ways: • Object literal. • Object constructor. • Object Literal: • The object literal is a simple way of creating an object using { } brackets. • Use comma (,) to separate multiple key-value pairs. • Example: • var emptyObject = {}; // object with no properties or methods • var person = { firstName: "John" }; // object with single property Only property or method name without value is not valid. var person = { firstName };  Wrong One
  • 13. Non-Primitive Data Types • Object Constructor: • using new keyword. • You can attach properties and methods using dot notation. • Optionally, you can also create properties using [ ] brackets and specifying property name as string. Example: var person = new Object(); // Attach properties and methods to person object person.firstName = “Thalaivar"; person["lastName"] = “Felix"; person.age = 25; person.getFullName = function () { return this.firstName + ' ' + this.lastName; }; // access properties & methods person.firstName; // Thalaivar person.lastName; // Felix person.getFullName(); // Thalaivar Felix var Alligator = new Object(); Aligator.firstName; Consider this code alone:  will return 'undefined' if you try to access properties or call methods that do not exist.
  • 14. Non-Primitive Data Types • Date: • provides Date object to work with date & time including days, months, years, hours, minutes, seconds and milliseconds. • Example: var date1 = new Date("3 march 2015"); var date2 = new Date("3 February, 2015"); var date3 = new Date("3rd February, 2015"); var date4 = new Date("2015 3 February"); var date5 = new Date("3 2015 February "); var date6 = new Date("February 3 2015"); var date7 = new Date("February 2015 3"); var date8 = new Date("3 2 2015"); Tue Mar 03 2015 00:00:00 GMT+0530 (India Standard Time) Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time) Invalid Date Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time) Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time) Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time) Tue Feb 03 2015 00:00:00 GMT+0530 (India Standard Time) Mon Mar 02 2015 00:00:00 GMT+0530 (India Standard Time) Tue Mar 03 2015 20:21:44 GMT+0530 (India Standard Time)
  • 15. Non-Primitive Data Types Array: An array is a special type of variable, which can store multiple values using special syntax. An array can be initialized using new keyword. Example: var stringArray = ["one", "two", "three"]; var numericArray = [1, 2, 3, 4]; var mixedArray = [1, "two", "three", 4]; var numericArray = new Array(2); numericArray[0] = 1; numericArray[1] = 2; concat() Returns new array by combining values of an array that is specified as parameter with existing array values. reverse() Reverses the elements of an array. Element at last index will be first and element at 0 index will be last. shift() Removes the first element from an array and returns that element. slice() Returns a new array with specified start to end elements. some() Returns true if at least one element in this array satisfies the condition in the callback function. sort() Sorts the elements of an array. Methods:
  • 16. DATATYPES EXAMPLE var length = 16; // Number var lastName = "Johnson"; // String var cars = ["Saab", "Volvo", "BMW"]; // Array var x = {firstName:"John", lastName:"Doe"}; // Object var x = "Volvo" + 16 + 4; Solve It : var x = 16 + 4 + "Volvo" ; JavaScript evaluates expressions from left to right. Volvo164 164Volvo
  • 17. FUNCTIONS • defined using Function keyword and provides functions similar to most of the scripting and programming languages. • A function can have one or more parameters, which will be supplied by the calling code and can be used inside a function. • JavaScript is a dynamic type scripting language, so a function parameter can have value of any data type. • Functions can also be defined with a built-in JavaScript function constructor called Function(). Example: var x = function (a, b) {return a * b};  This is Function Constructor var myFunction = new Function("a", "b", "return a * b"); var x = myFunction(4, 3);
  • 18. FUNCTIONS • Self-Invoking Functions: • A self-invoking expression is invoked (started) automatically, without being called. • Function expressions will execute automatically if the expression is followed by (). • You cannot self-invoke a function declaration. Example: (function () { var x = "Hello!!"; // invoke myself })(); function myFunction(a, b) { return a * b; } var txt = myFunction.toString(); toString() method returns the function as a string
  • 19. FUNCTIONS WITH ARGUMENTS function Alligator(firstName, lastName) { alert("Hello " + firstName + " " + lastName); } Alligator("Steve", "Jobs", "Mr."); Alligator("Bill"); Alligator();  display Hello Steve Jobs  display Hello Bill undefined  display Hello undefined undefined  A function can have one or more parameters, which will be supplied by the calling code and can be used inside a function.  If you pass less arguments then rest of the parameters will be undefined.  If you pass more arguments then additional arguments will be ignored.  can return zero or one value using return keyword. Example Example : function Sum(val1, val2) { return val1 + val2; };
  • 20. CONTROL STRUCTURES • IF CONDITION • IF ELSE CONDITION • ELSE IF CONDITION • SWITCH CONDITION • WHILE LOOP • DO WHILE LOOP • FOR LOOP • FOR IN LOOP • CONTINUE STATEMENT • BREAK STATEMENT Same Syntax and Same Format as in c# for (x in person) { text += person[x]; } Example for in: EXCEPTION HANDLING
  • 21. SCOPE • Scope in JavaScript defines accessibility of variables, objects and functions. • There are two types of scope in JavaScript. • Global scope • Local scope • Global scope: • Variables declared outside of any function become global variables. • Global variables can be accessed and modified from any function. • Local scope: • Variables declared inside any function with var keyword are called local variables. • Local variables cannot be accessed or modified outside the function declaration. var userName = "Bill"; function modifyUserName() { userName = "Steve"; }; function createUserName() { var userName = "Bill"; } function showUserName() { alert(userName); } createUserName(); showUserName(); // throws error
  • 22. JavaScript Hoisting: • a variable can be used before it has been declared. • JavaScript only hoists declarations, not initializations. • compiler moves all the declarations of variables and functions at the top so that there will not be any error. x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element var x; // Declare x var x = 5; // Initialize x elem = document.getElementById("demo"); // Find an element elem.innerHTML = "x is " + x + " and y is " + y; // Display x and y var y = 7; // Initialize y Output: 5 Output: x is 5 and y is undefined
  • 23. JSON • lightweight data interchange format. • JSON data is written as name/value pairs. • A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: "firstName":"John" • JSON objects are written inside curly braces. • JSON arrays are written inside square brackets. • JSON data can be converted into JavaScript Objects using parse method. JSON Example -JavaScript Object Notation { "employees":[ {"firstName":“Gowtham", "lastName":“raj"}, {"firstName":“Felix", "lastName":“Nirmal"}, ] } var obj = JSON.parse(text);
  • 24. JAVASCRIPT HTML DOM • Document Object Model • When a web page is loaded, the browser creates Document Object Model of the page.
  • 25. Define DOM ? • The W3C DOM standard is separated into 3 different parts: • Core DOM - standard model for all document types • XML DOM - standard model for XML documents • HTML DOM - standard model for HTML documents DOM Programming Interface: • In the DOM, all HTML elements are defined as objects. • The programming interface is the properties and methods of each object. • A property is a value that you can get or set (like changing the content of an HTML element). • A method is an action you can do (like add or deleting an HTML element).
  • 26. Example <script> document.getElementById("demo").innerHTML = "Hello World!"; </script> getElementById is a method, while innerHTML is a property. The getElementById Method  The 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 Property  The 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.
  • 27. HTML DOM DOCUMENT OBJECTS Methods Description document.getElementById(id) Find an element by element id document.getElementsByTagName(name) Find elements by tag name document.getElementsByClassName(name) Find elements by class name (represents your web page) Method Description element.innerHTML = new html content Change the inner HTML of an element element.attribute = new value Change the attribute value of an HTML element element.style.property = new style Change the style of an HTML element 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 document.write(text) Write into the HTML output stream Finding HTML Elements Adding Or Deleting HTML Elements Changing HTML Elements
  • 28. HTML DOM Elements • Finding HTML elements by id • Finding HTML elements by tag name • Finding HTML elements by class name • Finding HTML elements by CSS selectors • Finding HTML elements by HTML object collections var e = document.getElementById("intro"); var x = document.getElementsByTagName("p"); var x = document.getElementsByClassName("intro"); var x = document.querySelectorAll("p.intro"); var x = document.forms["frm1"]; var text = ""; var i; for (i = 0; i < x.length; i++) { text += x.elements[i].value + "<br>"; } document.getElementById("demo").innerHTML = text;
  • 29. GetElementByID() : <script type="text/javascript"> function getcube(){ var number=document.getElementById("number").value; alert(number*number*number); } </script> <form> Enter No:<input type="text" id="number" name="number"/><br/> <input type="button" value="cube" onclick="getcube()"/> </form> The document.getElementById() method returns the element of specified id.
  • 30. GetElementsByName() : <script type="text/javascript"> function totalelements() { var allgenders=document.getElementsByName("gender"); alert("Total Genders:"+allgenders.length); } </script> <form> Male:<input type="radio" name="gender" value="male"> Female:<input type="radio" name="gender" value="female"> <input type="button" onclick="totalelements()" value="Total Genders"> </form> The document.getElementsByName() method returns all the element of specified name.
  • 31. GetElementsByTagName() : <script type="text/javascript"> function countpara(){ var totalpara=document.getElementsByTagName("p"); alert("total p tags are: "+totalpara.length); } </script> <p>This is a pragraph</p> <p>Here we are going to count total number of paragraphs by getElementByTagName() method.</p> <p>Let's see the simple example</p> <button onclick="countpara()">count paragraph</button> The document.getElementsByTagName() method returns all the element of specified tag name.
  • 32. innerHTML property : <script type="text/javascript" > function showcommentform() { var data="Name:<input type='text' name='name'><br> Comment:<br><textarea rows='5' cols='80'></textarea> <br><input type='submit' value='Post Comment'>"; document.getElementById('mylocation').innerHTML=data; } </script> <form name="myForm"> <input type="button" value="comment" onclick="showcommentform()"> <div id="mylocation"></div> </form> The innerHTML property can be used to write the dynamic html on the html document.
  • 33. innerTEXT property : <script type="text/javascript" > function validate() { var msg; if(document.myForm.userPass.value.length>5){ msg="good"; } else{ msg="poor"; } document.getElementById('mylocation').innerText=msg; } </script> <form name="myForm"> <input type="password" value="" name="userPass" onkeyup="validate()"> Strength:<span id="mylocation">no strength</span> </form> The innerText property can be used to write the dynamic text on the html document.
  • 34. JAVASCRIPT HTML DOM - Changing HTML • The easiest way to modify the content of an HTML element is by using the innerHTML property. • Changing the Value of an Attribute : <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML = "New text!"; </script> <img id="myImage" src="smiley.gif"> <script> document.getElementById("myImage").src = "landscape.jpg"; </script>
  • 35. JAVASCRIPT HTML DOM - Changing CSS • To change the style of an HTML element • The HTML DOM allows you to execute code when an event occurs. • Events are generated by the browser when : • An element is clicked on • The page has loaded • Input fields are changed <p id="p2">Hello World!</p> <script> document.getElementById("p2").style.color = "blue"; </script> <h1 id="id1">My Heading 1</h1> <button type="button" onclick="document.getElementById('id1').style.c olor = 'red'"> Click Me!</button>
  • 36. JAVASCRIPT HTML DOM Animation • All animations should be relative to a container element. • The container element should be created with style = "position: relative". • The animation element should be created with style = "position: absolute". <div id ="container"> <div id ="animate">My animation will go here</div> </div> #container { width: 400px; height: 400px; position: relative; background: yellow; } #animate { width: 50px; height: 50px; position: absolute; background: red;}  JavaScript animations are done by programming gradual changes in an element's style.  The changes are called by a timer. When the timer interval is small, the animation looks continuous function myMove() {.getElementById("animate"); var pos = 0; var id = setInterval(frame, 5); function frame() { if (pos == 350) { clearInterval(id); } else { pos++; elem.style.top = pos + 'px'; elem.style.left = pos + 'px'; }}} var elem = document
  • 37. JAVASCRIPT HTML DOM EVENTS Examples of HTML events: • When a user clicks the mouse • When a web page has loaded • When an image has been loaded • When the mouse moves over an element • When an input field is changed • When an HTML form is submitted • When a user strokes a key <!DOCTYPE html> <html> <body> <h1 onclick="changeText(this)">Click on this text!</h1> <script> function changeText(id) { id.innerHTML = "Ooops!"; } </script> </body> </html> //INVOKES THE EVENTS
  • 38. JAVASCRIPT HTML DOM EVENTS • HTML Event Attributes: To assign events to HTML elements you can use event attributes. • HTML DOM allows you to assign events to HTML elements using JavaScript. • The onload and onunload Events • The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. • The onchange event is often used in combination with validation of input fields. <button onclick="displayDate()">Try it</button> <script> document.getElementById("myBtn").onclick = displayDate; </script> <body onload="checkCookies()"> <input type="text" id="fname" onchange="upperCase()"
  • 39. JavaScript HTML DOM EVENTLISTENER • The addEventListener() method • The addEventListener() method attaches an event handler to the specified element. • The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. • The addEventListener() method allows you to add many events to the same element, without overwriting existing events: document.getElementById("myBtn").addEventListener("click", displayDate); element.addEventListener("click", function(){ alert("Hello World!");}); //Add an Event Handler to an Element element.addEventListener("click", myFunction); element.addEventListener("click", mySecondFunction);