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>