SlideShare uma empresa Scribd logo
1 de 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>

Mais conteúdo relacionado

Mais procurados

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...Doug Jones
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScriptT11 Sessions
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorialadelaticleanu
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An IntroductionManvendra Singh
 
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 JavascriptArti Parab Academics
 
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 XMLMohammad Shaker
 
descriptive programming
descriptive programmingdescriptive programming
descriptive programmingAnand Dhana
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
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 MySQLArti Parab Academics
 
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 JavascriptArti Parab Academics
 
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 ATXCindy Royal
 

Mais procurados (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
 

Semelhante a Java script

JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript WorkshopPamela Fox
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)Ajay Khatri
 
JavaScript lesson 1.pptx
JavaScript lesson 1.pptxJavaScript lesson 1.pptx
JavaScript lesson 1.pptxMuqaddarNiazi1
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypesVarun C M
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java scriptnanjil1984
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to ProgrammingCindy Royal
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsBG Java EE Course
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentationAdhoura Academy
 
Web designing unit 4
Web designing unit 4Web designing unit 4
Web designing unit 4SURBHI SAROHA
 
JavaScript own objects(Web Technology)
JavaScript own objects(Web Technology)JavaScript own objects(Web Technology)
JavaScript own objects(Web Technology)Dhananjaysinh Jhala
 

Semelhante a 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)
 

Último

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dashnarutouzumaki53779
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate AgentsRyan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
Ryan Mahoney - Will Artificial Intelligence Replace Real Estate Agents
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dash
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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>