SlideShare a Scribd company logo
1 of 41
What is JavaScript?
 JavaScript is a client-side object-oriented scripting

language that is used to add interactivity to static
HTML pages.
 JavaScript is mainly used for validating user input in
web forms, reacting to user events, detecting
browsers, etc…
How to embed JavaScript in HTML?
 Scripts are embedded inside the HTML file using the

script tag <script>.

Scripts
Internal
The JavaScript code is embedded
inside the HTML file as follows:
<script type=”text/javascript”>
// JavaScript code goes here
</script>

External
The JavaScript code is written in an
external file with extension “.js” and
referenced in the HTML file as
follows:
<script type=”text/javascript”
src=”scriptFile.js”/>
Where to embed JavaScript in HTML?
 Script tag can be added either inside <head> section or the

<body> section of the HTML page.

Scripts
In Body

In Head
Scripts added to the <head> section
are to be executed when called.

Scripts added to the <body> section
are to be executed when the page
loads.

 Scripts are better to be included at the end of the HTML page in

order to prevent slow loading of pages.
JavaScript Syntax
 JavaScript statements ends with ;
 JavaScript is case sensitive
 JavaScript comments are like C++ and Java comments

// for single line comments and /* */ for multi-line
comments
JavaScript Output
 Writing to The HTML Document Output:
 To write HTML element using JavaScript we user
document.write("HTML Element");
 Example – To write a paragraph using JavaScript:
<script type=”text/javascript”>
document.write("<p>JavaScript Paragraph</p>");
</script>
JavaScript Output (Cont.)
 NOTE:

If you execute document.write after the document has
finished loading, the entire HTML page will be overwritten.
 Example:
<p>My Paragraph.</p>
<button onclick="myFunction()">Try it</button>
<script type=”text/javascript”>
function myFunction() {
document.write("<p>Oops! The document
disappeared!</p>");
}
</script>
JavaScript Output (Cont.)
JavaScript Variables
 Variable names must begin with a letter or $ or _.
 JavaScript is a weakly-typed language, meaning that variables are

declared without specifying data-types.
 You can declare variables with the var keyword.
 Examples:
var x = 1;
var y = 1.2;
var str = "Hello World";
var check = "true";
var cars=new Array("Saab", "Volvo", "BMW");
 Note:
If you assign a value to variable that has not yet been
declared, the variable will automatically be declared as
a GLOBALvariable.
JavaScript Objects
 To Create Object and add properties to it:
1.
var person = {
firstname : "John",
lastname : “Adam",
age
: 50
};
2.
Var person = new Object();
person.firstname="John";
person.lastname=“Adam";
person.age=50;


To Access Object properties:
1.
2.

name=person.lastname;
name=person["lastname"];
JavaScript Functions
 Syntax:

function functionname(argument1, argument2, …)
{
// some code to be executed
return value;
}
 To call:
var returnVar =
functionname(argument1, argument2, …);
JavaScript Operators
 JavaScript arithmetic operators (like C++ and Java):





+
/
*
++
-%
JavaScript assignment operators (like C++ and Java):
=
+=
-=
/=
JavaScript logical operators (like C++ and Java):
&& ||
!
JavaScript string concatenation operator:
+
JavaScript comparison operators :
!= ==
>
<
<=
>=
=== !==
JavaScript Conditions
 If...else if...else Statement:
 Syntax:
if (condition1)
{
// code to be executed if condition1 is true
}
else if (condition2)
{
// code to be executed if condition2 is true
}
else
{
// code to be executed if neither condition1 nor
condition2 is true
}
JavaScript Conditions (Cont.)
 Switch Statement:
 Syntax:
switch(n)
{
case 1:
// execute code block 1
break;
case 2:
// execute code block 2
break;
default:
// code to be executed if n is different from
case 1 and 2
}
JavaScript Loops
 For Loop:
 Syntax:
for (statement 1; statement 2; statement 3)
{
// code block to be executed
}
 For .. In Loop:
 Syntax:
for (variable in object)
{
// code to be executed
}
 Example:
var person={fname:"John", lname:“Adam", age:25};
for (x in person)
{
var personElement = person[x];
}
JavaScript Loops (cont.)
 While Loop:
 Syntax:
while (condition)
{
// code block to be executed
}
 Do .. While Loop:
 Syntax:
do
{
// code block to be executed
}
while (condition);
JavaScript Break and Continue
 Break Statement:
 It breaks the loop and continues executing the code after
the loop (if any).
 Syntax:
break;
 Continue Statement:
 It breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration
in the loop.
 Syntax:
continue;
JavaScript Strings
 String Length:
 You can get the length of a string using length property.
 Example:
var txt="Hello World";
document.write(txt.length);  11
 Finding a String in a String:
 You can find a string in another string using either indexOf()
or lastIndexOf() method.
 The method returns -1 if the specified text is not found.
 Example:
var str="Hello world";
var n = str.indexOf("l");  2
var m = str.lastIndexOf("l");  9
JavaScript Strings (Cont.)
 Matching Content:
 You can search for a matching content in a string using match()
method.
 This method returns the matching content if present, else it returns
null.
 Example:
var str="Hello World";
document.write(str.match("world"));  null
document.write(str.match("World"));  World
 Replacing Content:
 You can replace a specified value with another value in a string
using replace() method.
 Example:
var str=“Hello World"
var n=str.replace(“World",“FCI");  Hello FCI
JavaScript Strings (Cont.)
 Upper Case and Lower Case:
 You can convert a string to upper/lower case with the
methods toUpperCase() / toLowerCase().
 Example:
var txt="Hello World";
var txt1=txt.toUpperCase();  HELLO WORLD
var txt2=txt.toLowerCase();  hello world
 Convert a String to an Array:
 You can convert a string to an array with split() method.
 Example:
var str="a,b,c,d,e,f“;
var arr=str.split(",");  array {“a”, “b”, “c”, “d”, “e”, “f”}
JavaScript Strings (Cont.)
 Take part from a String:
 You can take part from a string using substring() method.
 Example:
var str="Hello World";
var substr=str.substring(2, 5);  llo
 Get Character from a String:
 You can get a char from a string using charAt() method.
 Example:
var str="Hello World";
var c=str.charAt(1);  e
JavaScript Strings (Cont.)
 Concatenate two Strings:
 You can concatenate two strings using concat()
method.
 Example:
var txt1="Hello";
var txt2="World";
var txt = txt1.concat(txt2);  HelloWorld
JavaScript Date
 Initiating a date:
1.
new Date(); // current date and time
2.
new Date(dateString);
3.
new, Date(year month, day, hours, minutes, seconds);


Example:
var n = new Date(79,5,24,11,33,o);
document.write(n);
Result:
Sun Jun 24 1979 11:33:00 GMT+0200 (Egypt Standard Time)



Example:
var n = new Date("June 24, 1979 11:33:00");
document.write(n);
Result:
Sun Jun 24 1979 11:33:00 GMT+0200 (Egypt Standard Time)
JavaScript Date (Cont.)
 Set Date:
1. setFullYear(year, month, day):
Example:
var myDate=new Date();
myDate.setFullYear(2010,0,14);
1. setDate(dateobject):
Example:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
 Compare Two Dates:
 To compare dates use >, <, ==, <=, >=
JavaScript Date (Cont.)
 getDate() Method:
 Used to get the day from a date.
 getMonth() Method :
 Used to get the month from a date.
 Note: Month starts from zero so add 1 to the retrun
result.
 getFullYear() Method :
 Used to get the year from a date.
JavaScript Math
 The Math object includes several mathematical constants

and methods.
 Math.PI:
 Constant 3.14








Math.round(number).
Math.floor(number).
Math.ceil(number).
Math.max(number1, number2).
Math.min(number1, number2).
Math.random():
 Return a random number between 0 and 1.
JavaScript HTML DOM
 The HTML DOM (Document Object Model) is a standard

for how to interact with (get, change, add, or delete) HTML
elements.
 Finding HTML Elements:
1.

2.
3.

By Id:

document.getElementById(“id");
By Tag Name:

document.getElementsByTagName(“tag");
By HTML Object Collections:

The following HTML object collections are accessible:
•
•
•
•

document.anchors
document.forms
document.images
document.links
JavaScript HTML DOM (Cont.)
 Example - Return the value of each element in

the form :
JavaScript HTML DOM (Cont.)
<html>
<body>
<form id="frm">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
<input type="submit" value="Submit" onClick="printValues()">
</form>
<script type="text/javascript">
function printValues() {
var form = document.forms["frm"];
for (var i=0 ; i < form.length ; i++) {
document.write(form.elements[i].value);
document.write("<br>");
}
}
</script>
</body>
</html>
JavaScript HTML DOM (Cont.)
 To access the value of the first name in the previous

example:
 var firstName = document.forms[“frm"]["fname"].value;
JavaScript HTML DOM (Cont.)
 Changing HTML:
 Changing the HTML Output Stream:


document.write()

 Changing HTML Content:


document.getElementById(id).innerHTML=new HTML

 Changing the Value of an Attribute:


document.getElementById(id).attribute=new value
JavaScript HTML DOM (Cont.)
 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

 Assign Events:


Using Attributes:




Example:
<button id= "myBtn" onclick="displayDate()">Try it</button>

Using HTML DOM:


Example:
document.getElementById("myBtn").onclick=function(){displayDate() };
JavaScript HTML DOM (Cont.)
 Mostly used Events:








Onclick
Onload
Onchange
Onmouseover
Onmouseout
Onmousedown
Onmouseup
JavaScript BOM
 BOM stands for Browser Object Model.
 Window:
 Window Size:




For Chrome, Firefox, Opera, and Safari:
 window.innerHeight - the inner height of the browser window
 window.innerWidth - the inner width of the browser window
For Internet Explorer 8, 7, 6, 5:
 document.documentElement.clientHeight
 document.documentElement.clientWidth
or
 document.body.clientHeight
 document.body.clientWidth
JavaScript Browser BOM (Cont.)
 Some Window Methods:
 window.open()
 window.close()
 window.resizeTo()
 Window Frames:
 window.frames

 Screen:
 Syntax: window.screen or screen
 To get the available screen width and height (Without
taskbars or scrolling bars):



screen.availWidth
screen.availHeight
JavaScript Browser BOM (Cont.)
 Popup Alert:
 Alert Box:



Syntax: window.alert(“Message");
A popup with ok button.

 Confirm Box:



Syntax: window.confirm(“Message");
A popup with ok and cancel buttons, returns true if the user clicked on
ok and false if the user clicked on cancel.

 Prompt Box:



Syntax: window.prompt(“Message","Default value for input");
A popup with a text box for user input, ok and cancel buttons, returns
the user input if he user clicked ok and null if the user clicked on cancel.

 NOTE:

To display line breaks inside a popup box, use n.
JavaScript Browser BOM (Cont.)
 Location:
 Syntax: window.location or location
 location.href: returns the URL of the current page.
 location.pathname: returns the path and filename of the
current page.
 location.hostname: returns the domain name of the web host.
 location.port: returns the port of the web host (80 or 443).
 location.protocol: returns the web protocol used (http:// or
https://).
 location.assign(URL): loads a new page.
JavaScript Browser BOM (Cont.)
 History:
 history.back(): same as clicking back in the browser.
 history.forward(): same as clicking forward in the
browser.
TASK
 Create a page like the following, and
then validate for empty fields.
 On Submit:
1.
If Username is empty: Alert
“Username must be filled out.”.
2.
If Password is empty: Alert
“Password must be filled out.”.
3.
Else: Alert “Done.”.

What needed to be known?
•To define a variable:
var variable_name =
variable_value;
•To define a function:
function
function_name(parameters…)
{
// Code goes here
return value;
}
•To get form:
document.forms[“form id“];
•To get value of element in form:
document.forms[“form id“][“name
attribute of the element”].value;
•To Alert a message:
Alert(“Message”);
TASK (Cont.)
<html>
<head>
<script type="text/javascript">
function validateForm(){
var username = document.forms["myForm"]["username"].value;
var password = document.forms["myForm"]["password"].value
if (username == null || username == "") {
alert("Username must be filled out.");
return false;
} else if (password == null || password == "") {
alert("Password must be filled out.");
return false;
} else {
alert("Done.");
return true;
}
}
</script>
</head>
TASK (Cont.)
<body>
<form name="myForm" onsubmit="return
validateForm()">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

More Related Content

What's hot

JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
adelaticleanu
 

What's hot (20)

JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
FYBSC IT Web Programming Unit III Core Javascript
FYBSC IT Web Programming Unit III  Core JavascriptFYBSC IT Web Programming Unit III  Core Javascript
FYBSC IT Web Programming Unit III Core Javascript
 
C# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XMLC# Advanced L03-XML+LINQ to XML
C# Advanced L03-XML+LINQ to XML
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programming
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
FYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III JavascriptFYBSC IT Web Programming Unit III Javascript
FYBSC IT Web Programming Unit III Javascript
 
Javascript
JavascriptJavascript
Javascript
 
Intro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATXIntro to Programming for Communicators - Hacks/Hackers ATX
Intro to Programming for Communicators - Hacks/Hackers ATX
 

Similar to Java script

Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 

Similar to Java script (20)

Javascript
JavascriptJavascript
Javascript
 
Web programming
Web programmingWeb programming
Web programming
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptx
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Javascript
JavascriptJavascript
Javascript
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Javascript
JavascriptJavascript
Javascript
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Java script
Java scriptJava script
Java script
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
FSJavaScript.ppt
FSJavaScript.pptFSJavaScript.ppt
FSJavaScript.ppt
 
Javascript
JavascriptJavascript
Javascript
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4
 
JavaScript own objects(Web Technology)
JavaScript own objects(Web Technology)JavaScript own objects(Web Technology)
JavaScript own objects(Web Technology)
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Java script

  • 1.
  • 2. What is JavaScript?  JavaScript is a client-side object-oriented scripting language that is used to add interactivity to static HTML pages.  JavaScript is mainly used for validating user input in web forms, reacting to user events, detecting browsers, etc…
  • 3. How to embed JavaScript in HTML?  Scripts are embedded inside the HTML file using the script tag <script>. Scripts Internal The JavaScript code is embedded inside the HTML file as follows: <script type=”text/javascript”> // JavaScript code goes here </script> External The JavaScript code is written in an external file with extension “.js” and referenced in the HTML file as follows: <script type=”text/javascript” src=”scriptFile.js”/>
  • 4. Where to embed JavaScript in HTML?  Script tag can be added either inside <head> section or the <body> section of the HTML page. Scripts In Body In Head Scripts added to the <head> section are to be executed when called. Scripts added to the <body> section are to be executed when the page loads.  Scripts are better to be included at the end of the HTML page in order to prevent slow loading of pages.
  • 5. JavaScript Syntax  JavaScript statements ends with ;  JavaScript is case sensitive  JavaScript comments are like C++ and Java comments // for single line comments and /* */ for multi-line comments
  • 6. JavaScript Output  Writing to The HTML Document Output:  To write HTML element using JavaScript we user document.write("HTML Element");  Example – To write a paragraph using JavaScript: <script type=”text/javascript”> document.write("<p>JavaScript Paragraph</p>"); </script>
  • 7. JavaScript Output (Cont.)  NOTE: If you execute document.write after the document has finished loading, the entire HTML page will be overwritten.  Example: <p>My Paragraph.</p> <button onclick="myFunction()">Try it</button> <script type=”text/javascript”> function myFunction() { document.write("<p>Oops! The document disappeared!</p>"); } </script>
  • 9. JavaScript Variables  Variable names must begin with a letter or $ or _.  JavaScript is a weakly-typed language, meaning that variables are declared without specifying data-types.  You can declare variables with the var keyword.  Examples: var x = 1; var y = 1.2; var str = "Hello World"; var check = "true"; var cars=new Array("Saab", "Volvo", "BMW");  Note: If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBALvariable.
  • 10. JavaScript Objects  To Create Object and add properties to it: 1. var person = { firstname : "John", lastname : “Adam", age : 50 }; 2. Var person = new Object(); person.firstname="John"; person.lastname=“Adam"; person.age=50;  To Access Object properties: 1. 2. name=person.lastname; name=person["lastname"];
  • 11. JavaScript Functions  Syntax: function functionname(argument1, argument2, …) { // some code to be executed return value; }  To call: var returnVar = functionname(argument1, argument2, …);
  • 12. JavaScript Operators  JavaScript arithmetic operators (like C++ and Java):     + / * ++ -% JavaScript assignment operators (like C++ and Java): = += -= /= JavaScript logical operators (like C++ and Java): && || ! JavaScript string concatenation operator: + JavaScript comparison operators : != == > < <= >= === !==
  • 13. JavaScript Conditions  If...else if...else Statement:  Syntax: if (condition1) { // code to be executed if condition1 is true } else if (condition2) { // code to be executed if condition2 is true } else { // code to be executed if neither condition1 nor condition2 is true }
  • 14. JavaScript Conditions (Cont.)  Switch Statement:  Syntax: switch(n) { case 1: // execute code block 1 break; case 2: // execute code block 2 break; default: // code to be executed if n is different from case 1 and 2 }
  • 15. JavaScript Loops  For Loop:  Syntax: for (statement 1; statement 2; statement 3) { // code block to be executed }  For .. In Loop:  Syntax: for (variable in object) { // code to be executed }  Example: var person={fname:"John", lname:“Adam", age:25}; for (x in person) { var personElement = person[x]; }
  • 16. JavaScript Loops (cont.)  While Loop:  Syntax: while (condition) { // code block to be executed }  Do .. While Loop:  Syntax: do { // code block to be executed } while (condition);
  • 17. JavaScript Break and Continue  Break Statement:  It breaks the loop and continues executing the code after the loop (if any).  Syntax: break;  Continue Statement:  It breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.  Syntax: continue;
  • 18. JavaScript Strings  String Length:  You can get the length of a string using length property.  Example: var txt="Hello World"; document.write(txt.length);  11  Finding a String in a String:  You can find a string in another string using either indexOf() or lastIndexOf() method.  The method returns -1 if the specified text is not found.  Example: var str="Hello world"; var n = str.indexOf("l");  2 var m = str.lastIndexOf("l");  9
  • 19. JavaScript Strings (Cont.)  Matching Content:  You can search for a matching content in a string using match() method.  This method returns the matching content if present, else it returns null.  Example: var str="Hello World"; document.write(str.match("world"));  null document.write(str.match("World"));  World  Replacing Content:  You can replace a specified value with another value in a string using replace() method.  Example: var str=“Hello World" var n=str.replace(“World",“FCI");  Hello FCI
  • 20. JavaScript Strings (Cont.)  Upper Case and Lower Case:  You can convert a string to upper/lower case with the methods toUpperCase() / toLowerCase().  Example: var txt="Hello World"; var txt1=txt.toUpperCase();  HELLO WORLD var txt2=txt.toLowerCase();  hello world  Convert a String to an Array:  You can convert a string to an array with split() method.  Example: var str="a,b,c,d,e,f“; var arr=str.split(",");  array {“a”, “b”, “c”, “d”, “e”, “f”}
  • 21. JavaScript Strings (Cont.)  Take part from a String:  You can take part from a string using substring() method.  Example: var str="Hello World"; var substr=str.substring(2, 5);  llo  Get Character from a String:  You can get a char from a string using charAt() method.  Example: var str="Hello World"; var c=str.charAt(1);  e
  • 22. JavaScript Strings (Cont.)  Concatenate two Strings:  You can concatenate two strings using concat() method.  Example: var txt1="Hello"; var txt2="World"; var txt = txt1.concat(txt2);  HelloWorld
  • 23. JavaScript Date  Initiating a date: 1. new Date(); // current date and time 2. new Date(dateString); 3. new, Date(year month, day, hours, minutes, seconds);  Example: var n = new Date(79,5,24,11,33,o); document.write(n); Result: Sun Jun 24 1979 11:33:00 GMT+0200 (Egypt Standard Time)  Example: var n = new Date("June 24, 1979 11:33:00"); document.write(n); Result: Sun Jun 24 1979 11:33:00 GMT+0200 (Egypt Standard Time)
  • 24. JavaScript Date (Cont.)  Set Date: 1. setFullYear(year, month, day): Example: var myDate=new Date(); myDate.setFullYear(2010,0,14); 1. setDate(dateobject): Example: var myDate=new Date(); myDate.setDate(myDate.getDate()+5);  Compare Two Dates:  To compare dates use >, <, ==, <=, >=
  • 25. JavaScript Date (Cont.)  getDate() Method:  Used to get the day from a date.  getMonth() Method :  Used to get the month from a date.  Note: Month starts from zero so add 1 to the retrun result.  getFullYear() Method :  Used to get the year from a date.
  • 26. JavaScript Math  The Math object includes several mathematical constants and methods.  Math.PI:  Constant 3.14       Math.round(number). Math.floor(number). Math.ceil(number). Math.max(number1, number2). Math.min(number1, number2). Math.random():  Return a random number between 0 and 1.
  • 27. JavaScript HTML DOM  The HTML DOM (Document Object Model) is a standard for how to interact with (get, change, add, or delete) HTML elements.  Finding HTML Elements: 1. 2. 3. By Id:  document.getElementById(“id"); By Tag Name:  document.getElementsByTagName(“tag"); By HTML Object Collections:  The following HTML object collections are accessible: • • • • document.anchors document.forms document.images document.links
  • 28. JavaScript HTML DOM (Cont.)  Example - Return the value of each element in the form :
  • 29. JavaScript HTML DOM (Cont.) <html> <body> <form id="frm"> First name: <input type="text" name="fname" value="Donald"><br> Last name: <input type="text" name="lname" value="Duck"><br> <input type="submit" value="Submit" onClick="printValues()"> </form> <script type="text/javascript"> function printValues() { var form = document.forms["frm"]; for (var i=0 ; i < form.length ; i++) { document.write(form.elements[i].value); document.write("<br>"); } } </script> </body> </html>
  • 30. JavaScript HTML DOM (Cont.)  To access the value of the first name in the previous example:  var firstName = document.forms[“frm"]["fname"].value;
  • 31. JavaScript HTML DOM (Cont.)  Changing HTML:  Changing the HTML Output Stream:  document.write()  Changing HTML Content:  document.getElementById(id).innerHTML=new HTML  Changing the Value of an Attribute:  document.getElementById(id).attribute=new value
  • 32. JavaScript HTML DOM (Cont.)  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  Assign Events:  Using Attributes:   Example: <button id= "myBtn" onclick="displayDate()">Try it</button> Using HTML DOM:  Example: document.getElementById("myBtn").onclick=function(){displayDate() };
  • 33. JavaScript HTML DOM (Cont.)  Mostly used Events:        Onclick Onload Onchange Onmouseover Onmouseout Onmousedown Onmouseup
  • 34. JavaScript BOM  BOM stands for Browser Object Model.  Window:  Window Size:   For Chrome, Firefox, Opera, and Safari:  window.innerHeight - the inner height of the browser window  window.innerWidth - the inner width of the browser window For Internet Explorer 8, 7, 6, 5:  document.documentElement.clientHeight  document.documentElement.clientWidth or  document.body.clientHeight  document.body.clientWidth
  • 35. JavaScript Browser BOM (Cont.)  Some Window Methods:  window.open()  window.close()  window.resizeTo()  Window Frames:  window.frames  Screen:  Syntax: window.screen or screen  To get the available screen width and height (Without taskbars or scrolling bars):   screen.availWidth screen.availHeight
  • 36. JavaScript Browser BOM (Cont.)  Popup Alert:  Alert Box:   Syntax: window.alert(“Message"); A popup with ok button.  Confirm Box:   Syntax: window.confirm(“Message"); A popup with ok and cancel buttons, returns true if the user clicked on ok and false if the user clicked on cancel.  Prompt Box:   Syntax: window.prompt(“Message","Default value for input"); A popup with a text box for user input, ok and cancel buttons, returns the user input if he user clicked ok and null if the user clicked on cancel.  NOTE: To display line breaks inside a popup box, use n.
  • 37. JavaScript Browser BOM (Cont.)  Location:  Syntax: window.location or location  location.href: returns the URL of the current page.  location.pathname: returns the path and filename of the current page.  location.hostname: returns the domain name of the web host.  location.port: returns the port of the web host (80 or 443).  location.protocol: returns the web protocol used (http:// or https://).  location.assign(URL): loads a new page.
  • 38. JavaScript Browser BOM (Cont.)  History:  history.back(): same as clicking back in the browser.  history.forward(): same as clicking forward in the browser.
  • 39. TASK  Create a page like the following, and then validate for empty fields.  On Submit: 1. If Username is empty: Alert “Username must be filled out.”. 2. If Password is empty: Alert “Password must be filled out.”. 3. Else: Alert “Done.”. What needed to be known? •To define a variable: var variable_name = variable_value; •To define a function: function function_name(parameters…) { // Code goes here return value; } •To get form: document.forms[“form id“]; •To get value of element in form: document.forms[“form id“][“name attribute of the element”].value; •To Alert a message: Alert(“Message”);
  • 40. TASK (Cont.) <html> <head> <script type="text/javascript"> function validateForm(){ var username = document.forms["myForm"]["username"].value; var password = document.forms["myForm"]["password"].value if (username == null || username == "") { alert("Username must be filled out."); return false; } else if (password == null || password == "") { alert("Password must be filled out."); return false; } else { alert("Done."); return true; } } </script> </head>
  • 41. TASK (Cont.) <body> <form name="myForm" onsubmit="return validateForm()"> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="Submit"> </form> </body> </html>