SlideShare a Scribd company logo
Javascript
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 (20)

PPTX
Php Tutorial
pratik tambekar
 
PPTX
Types of Selectors (HTML)
Deanne Alcalde
 
PPTX
Secure Socket Layer (SSL)
Samip jain
 
PPT
PHP - Introduction to PHP AJAX
Vibrant Technologies & Computers
 
PPTX
Files in php
sana mateen
 
PPT
cascading style sheet ppt
abhilashagupta
 
PPT
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
PPT
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
PPTX
PHP FUNCTIONS
Zeeshan Ahmed
 
PPTX
Rsa Crptosystem
Amlan Patel
 
PPT
Php Presentation
Manish Bothra
 
PPT
Intro to CSS Selectors in Drupal
cgmonroe
 
PPTX
Css types internal, external and inline (1)
Webtech Learning
 
PPTX
PHP Form Validation Technique
Morshedul Arefin
 
PPT
Hyperlinks in HTML
Aarti P
 
PPT
CSS Basics
WordPress Memphis
 
PPTX
HTML Forms
Nisa Soomro
 
PPTX
Date and time functions in mysql
V.V.Vanniaperumal College for Women
 
PPT
Introduction To PHP
Shweta A
 
Php Tutorial
pratik tambekar
 
Types of Selectors (HTML)
Deanne Alcalde
 
Secure Socket Layer (SSL)
Samip jain
 
PHP - Introduction to PHP AJAX
Vibrant Technologies & Computers
 
Files in php
sana mateen
 
cascading style sheet ppt
abhilashagupta
 
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
PHP FUNCTIONS
Zeeshan Ahmed
 
Rsa Crptosystem
Amlan Patel
 
Php Presentation
Manish Bothra
 
Intro to CSS Selectors in Drupal
cgmonroe
 
Css types internal, external and inline (1)
Webtech Learning
 
PHP Form Validation Technique
Morshedul Arefin
 
Hyperlinks in HTML
Aarti P
 
CSS Basics
WordPress Memphis
 
HTML Forms
Nisa Soomro
 
Date and time functions in mysql
V.V.Vanniaperumal College for Women
 
Introduction To PHP
Shweta A
 

Similar to Javascript (20)

PPTX
Javascript analysis
Uchitha Bandara
 
PPT
Javascript
Manav Prasad
 
PDF
Javascript
20261A05H0SRIKAKULAS
 
PPTX
Front end fundamentals session 1: javascript core
Web Zhao
 
PPTX
javascript client side scripting la.pptx
lekhacce
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
Java script summary
maamir farooq
 
PPTX
js.pptx
SuhaibKhan62
 
PPTX
JavaScript.pptx
KennyPratheepKumar
 
PDF
Basics of JavaScript
Bala Narayanan
 
KEY
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
PPTX
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
PPTX
JavaScripts & jQuery
Asanka Indrajith
 
PPTX
JavaScript Lecture notes.pptx
NishaRohit6
 
PPT
An introduction to javascript
MD Sayem Ahmed
 
PPTX
Java script
bosybosy
 
PPTX
Final Java-script.pptx
AlkanthiSomesh
 
PPTX
WT Unit-3 PPT.pptx
TusharTikia
 
PPTX
Javascript 101
Shlomi Komemi
 
PDF
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
Javascript analysis
Uchitha Bandara
 
Javascript
Manav Prasad
 
Front end fundamentals session 1: javascript core
Web Zhao
 
javascript client side scripting la.pptx
lekhacce
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
Java script summary
maamir farooq
 
js.pptx
SuhaibKhan62
 
JavaScript.pptx
KennyPratheepKumar
 
Basics of JavaScript
Bala Narayanan
 
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
gdscWorkShopJavascriptintroductions.pptx
sandeshshahapur
 
JavaScripts & jQuery
Asanka Indrajith
 
JavaScript Lecture notes.pptx
NishaRohit6
 
An introduction to javascript
MD Sayem Ahmed
 
Java script
bosybosy
 
Final Java-script.pptx
AlkanthiSomesh
 
WT Unit-3 PPT.pptx
TusharTikia
 
Javascript 101
Shlomi Komemi
 
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
Ad

Recently uploaded (20)

PPTX
00-ClimateChangeImpactCIAProcess_PPTon23.12.2024-ByDr.VijayanGurumurthyIyer1....
praz3
 
PPTX
Abstract Data Types (ADTs) in Data Structures
mwaslam2303
 
PDF
BEE331-Week 04-SU25.pdf semiconductors UW
faemoxley
 
PDF
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
PDF
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
PPTX
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
PPTX
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
PDF
Comparative Analysis of the Use of Iron Ore Concentrate with Different Binder...
msejjournal
 
PDF
IEEE EMBC 2025 「Improving electrolaryngeal speech enhancement via a represent...
NU_I_TODALAB
 
PPTX
Presentation on Foundation Design for Civil Engineers.pptx
KamalKhan563106
 
PDF
Web Technologies - Chapter 3 of Front end path.pdf
reemaaliasker
 
PDF
NOISE CONTROL ppt - SHRESTH SUDHIR KOKNE
SHRESTHKOKNE
 
PDF
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
PDF
Non Text Magic Studio Magic Design for Presentations L&P.pdf
rajpal7872
 
PPTX
ENSA_Module_8.pptx_nice_ipsec_presentation
RanaMukherjee24
 
PDF
Natural Language processing and web deigning notes
AnithaSakthivel3
 
PPTX
Fluid statistics and Numerical on pascal law
Ravindra Kolhe
 
PDF
1_ISO Certifications by Indian Industrial Standards Organisation.pdf
muhammad2010960
 
PDF
An Evaluative Study on Performance Growth Plan of ICICI Mutual Fund and SBI M...
PoonamKilaniya
 
PDF
LEARNING CROSS-LINGUAL WORD EMBEDDINGS WITH UNIVERSAL CONCEPTS
kjim477n
 
00-ClimateChangeImpactCIAProcess_PPTon23.12.2024-ByDr.VijayanGurumurthyIyer1....
praz3
 
Abstract Data Types (ADTs) in Data Structures
mwaslam2303
 
BEE331-Week 04-SU25.pdf semiconductors UW
faemoxley
 
MOBILE AND WEB BASED REMOTE BUSINESS MONITORING SYSTEM
ijait
 
A presentation on the Urban Heat Island Effect
studyfor7hrs
 
Water resources Engineering GIS KRT.pptx
Krunal Thanki
 
ETP Presentation(1000m3 Small ETP For Power Plant and industry
MD Azharul Islam
 
Comparative Analysis of the Use of Iron Ore Concentrate with Different Binder...
msejjournal
 
IEEE EMBC 2025 「Improving electrolaryngeal speech enhancement via a represent...
NU_I_TODALAB
 
Presentation on Foundation Design for Civil Engineers.pptx
KamalKhan563106
 
Web Technologies - Chapter 3 of Front end path.pdf
reemaaliasker
 
NOISE CONTROL ppt - SHRESTH SUDHIR KOKNE
SHRESTHKOKNE
 
勉強会資料_An Image is Worth More Than 16x16 Patches
NABLAS株式会社
 
Non Text Magic Studio Magic Design for Presentations L&P.pdf
rajpal7872
 
ENSA_Module_8.pptx_nice_ipsec_presentation
RanaMukherjee24
 
Natural Language processing and web deigning notes
AnithaSakthivel3
 
Fluid statistics and Numerical on pascal law
Ravindra Kolhe
 
1_ISO Certifications by Indian Industrial Standards Organisation.pdf
muhammad2010960
 
An Evaluative Study on Performance Growth Plan of ICICI Mutual Fund and SBI M...
PoonamKilaniya
 
LEARNING CROSS-LINGUAL WORD EMBEDDINGS WITH UNIVERSAL CONCEPTS
kjim477n
 
Ad

Javascript

  • 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);