SlideShare uma empresa Scribd logo
1 de 62
IFI7174.DT – Lesson 3
JavaScript
JavaScript
• Is a lightweight
– Object Oriented Programming (OOP) language
• Why JavaScript?
– It helps you to add behaviors into your webpages
– It changes HTML Content
– It changes HTML Styles (CSS)
2015 @ Sonia Sousa 2
JavaScript
• Is typically used in browsers
– to power dynamic websites.
• add functionality;
• validate input, and
• communicate with web servers
• JS code is loaded and ran
– Inline within HTML code <script> tags
– In blocks
• <script> JS code </script>
2015 @ Sonia Sousa 3
JavaScript
• Can be:
– Load as an external scripts
• External
– Inline within HTML code <script> tags
– Embedded
• <head>
– functions
• <body>
– event change
<script src="myScript.js"></script>
<script>document.write("<h1>Hello, there!</h1>"); </script>
<head>
<title>Embedded JS Example</title>
<script>
document.write("Oops");
</script>
</head>
2015 @ Sonia Sousa 4
External JS Advantages
• It separates HTML and code
• It makes HTML and JavaScript easier to read
and maintain
• Cached JavaScript files can speed up page
loads
2015 @ Sonia Sousa 5
JS Embedded in HTML
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
<button onclick="myFunction()">Try it</button>
• <head> </head>
• <body> </body>
2015 @ Sonia Sousa 6
JS inline with HTML
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
2015 @ Sonia Sousa 7
• <body> </body>
The Document Object
• When an HTML document is loaded into a web
browser,
– it becomes a document object.
• The document object
– provides properties and methods
• to access all node objects, from within JavaScript
– represents
• the root node of the HTML document
– It controls the
• element, text, attribute, and comment nodes
2015 @ Sonia Sousa 8
Document Object Model (DOM)
• starts by…
1. browser window itself
2. document page,
3. the elements included on
the page; and
4. their attributes.
Source: Wikipedia
The object hierarchy
2015 @ Sonia Sousa 9
How JS and the DOM cooperate
• When a web page is loaded,
– The browser creates a DOM of the page
• Like a tree
Source: w3schools2015 @ Sonia Sousa 10
DOM
Window
documen
t
meta
Textbox
Radio
button
head body
form[] link Imagestitle div ul
li
Establish the Order of things
2015 @ Sonia Sousa 11
How JS and the DOM cooperate
• JavaScript can change
– the HTML elements in the page
– the HTML attributes in the page
– the CSS styles in the page
• JavaScript can react to
– the events in the page
• This is done by
– object notation
2015 @ Sonia Sousa 12
Object notation
• Access to elements
– be referenced using dot notation
• starting with the highest-level object
– (i.e., window).
» But as the window is in the top hierarchy do not need to
be refereed
– Objects can be referred to
• by name; or id; or by their position on the page
document.getElementById("demo").innerHTML = "Hello JavaScript”;
2015 @ Sonia Sousa 13
JavaScript Syntax
• Basic rules
– Ends with ; (semi-colons)
– ! is case sensitive !
• Comments
– double slash (//)
• 1 line comment
– between /* and */
• More than 1 line comment
2015 @ Sonia Sousa 14
JS programs
• A program is a
– list of "instructions” to be "executed" by the
computer
– These instructions are called statements
• JS statements are separated by semicolons ;
• A statement composed of:
– Values, Operators, Expressions, Keywords, and
Comments.
2015 @ Sonia Sousa 15
JavaScript statements
• Statements includes
– Values, Operators, Expressions, Keywords, and
Comments
– Values are
• Literal or variables
– Functions are
• a block of code that can execute some action
– Events are
• actions triggered by someone
2015 @ Sonia Sousa 16
Values
• Literal values are
– Numbers
• with or without decimals (10.50 or 1001)
– Strings
• Double or single quotes ("John Doe” ‘John Doe’)
– Variables
• Are used to store data (var x; x = 6;)
2015 @ Sonia Sousa 17
JS Keywords
• To identify the JavaScript action to be performed.
Keyword Description
break Terminates a switch or a loop
continue Jumps out of a loop and starts at the top
do ... while
Executes a block of statements, and repeats the block, while a condition is
true
for Marks a block of statements to be executed, as long as a condition is true
function Declares a function
if ... else Marks a block of statements to be executed, depending on a condition
return Exits a function
switch Marks a block of statements to be executed, depending on different cases
try ... catch Implements error handling to a block of statements
var Declares a variable
2015 @ Sonia Sousa 18
JS Statements
• A statement is the line of code that tell
– the browser to execute something
document.getElementById("demo").innerHTML = "Hello!";
• JavaScript statements
Var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z;
2015 @ Sonia Sousa 19
JavaScript Statements
• Giving a command to the browser
<script>
function myFunction()
{
document.write("Oops! The document
disappeared!");
}
</script>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.write("Oops! The document
disappeared!");
}
</script>
2015 @ Sonia Sousa 20
JS code and Blocks
JS code blocks
JS functions
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
<script>
1. document.write("<h1>Hello, there!</h1>");
2. document.getElementById("demo").innerHTML="Hello Dolly";
3. document.getElementById("myDIV").innerHTML="How are you?”;
</script>
• Define statements to be executed together
• JavaScript functions are statements grouped in blocks
2015 @ Sonia Sousa 21
JS and HTML Styles (CSS)
• JavaScript can change
– HTML elements
– (CSS) Styles
– Or validate input (data)
• Using methods, conditional and fuctions
• For instance, to change the text
– It uses getElementById() method
document.getElementById("demo").innerHTML = "Hello
JavaScript”;
2015 @ Sonia Sousa 22
JavaScript Variables
• variables are "containers" of information
– We can name it using letters (like x)
• The variable can contain
– Letter, numerical values or expressions
var x=5;
var y=6;
var z=x+y;
"declaring" a variable
assign a value
var carname;
carname="Volvo";
2015 @ Sonia Sousa 23
Declaring (Creating) JS Variables
• Primitive data types
– Number
var x = 5;
– String
var carname = “Volvo XC60";
– Boolean
var x = true;
var y = false;
2015 @ Sonia Sousa 24
Declaring (Creating) JS Variables
• JS Array
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
var cars = ["Saab", "Volvo", "BMW"];
• JavaScript Objects
var person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};
2015 @ Sonia Sousa 25
Object (Properties and Methods)
• data (variables) as objects
– they have properties
– they have methods
Object Properties Methods
Car car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
car.start()
car.drive()
car.brake()
2015 @ Sonia Sousa 26
JS Operators
• Operators are used to
– assign values to variables using (=)
• var x = 5; var y = 6;
• Arithmetic operators
• Comparison operators
• Logical operators
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
2015 @ Sonia Sousa 27
JS Operators
Opera
tors
example results
+ x=y+2 Addition x=7
- x=y-2 Subtraction x=3
* x=y*2 Multiplication x=10
/ x=y/2 Division x=2.5
++ x=++y Increment x=6
-- x=--y Decrement x=4
== x==8 equal to false
!= x!=8 Not equal to true
> x>8 greater than false
< x<8 less than true
>= x>=8 greater than or equal to false
<= x<=8 Less tan or equal to true
&& (x < 10 && y > 1) and true
|| (x==5 || y==5) or false
! !(x==y) not true
Logical
Comparison
Arithmetic
2015 @ Sonia Sousa 28
Assignment Operators
Operator Example Same as
Resul
t
= x=y
+= x+=y x=x+y
-= x-=y x=y-2
*= x*=y x=x*y
++ x=++y Increment x=6
-- x=--y Decrement x=4
== x==8
!= x!=8
> x>8
< x<8
>= x>=8
<= x<=8
&& (x < 10 && y > 1)
|| (x==5 || y==5)
! !(x==y)
2015 @ Sonia Sousa 29
JS Expressions
• Combine values, variables, and operators
– The computation is called an evaluation
• 5 * 10 evaluates to 50
– can also contain variable values
• x * 10
• "John" + " " + "Doe"
2015 @ Sonia Sousa 30
JavaScript Functions
• is a block of code designed to perform a
particular task.
– A JavaScript function is executed when
"something" invokes it (calls it).
function name(parameter1, parameter2,
parameter3) {
code to be executed
}
2015 @ Sonia Sousa 31
Function Syntax
function name(parameter1, parameter2, parameter3) {
code to be executed
}
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()”> Try it </button>
</body>
</html>
Function name
Code to execute
Call function
2015 @ Sonia Sousa 32
Function Invocation
• The code inside the function will execute
when "something” happens
– an event occurs (when a user clicks a button)
– it is invoked (called) from JavaScript code
– Automatically (self-invoked)
2015 @ Sonia Sousa 33
JavaScript Functions
• A block of code that will be executed when
"someone" calls it
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
Code Block
Call
function
2015 @ Sonia Sousa 34
Return values
• Functions often compute a return value.
var x = myFunction(4, 3);
// Function is called, return value will end up in
x
function myFunction(a, b) {
return a * b;
// Function returns the product of a and b
}
2015 @ Sonia Sousa 35
Function with Arguments
</head> <body>
<button onclick="myFunction()">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " +
job);
}
</script>
2015 @ Sonia Sousa 36
<script>
myFunction(argument1,argument2)
{
some code
}
</script>
Using ID with function
</head> <body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML=myFunction(4,3);
</script>
<script>
function myFunction(a,b)
{
return a*b;
}
</script>
2015 @ Sonia Sousa 37
<script>
myFunction(argument1,argument2)
{
some code
}
</script>
JavaScript Events
• Is something the browser does, or something a user does
– Event handlers
• used to handle, and verify, user input, user actions, and browser
actions.
– HTML events
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
<some-HTML-element some-event="some JavaScript">
<button onclick="this.innerHTML=Date()">The time is?
</button>
2015 @ Sonia Sousa 38
HTML DOM Events
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout
The user moves the mouse away from an HTML
element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
onmouseenter occurs when the pointer is moved onto an element
onmousedown the user presses a mouse button over an element
2015 @ Sonia Sousa 39
JavaScript Strings
• String have Properties and Methods
– Primitive value
• var firstName = "John”
var x = "John";
– String objects
• var firstName = new String("John")
var y = new String("John");
2015 @ Sonia Sousa 40
JavaScript Strings
Method Description
charAt() Returns the character at the specified index (position)
concat() Joins two or more strings, and returns a copy of the joined strings
indexOf()
Returns the position of the first found occurrence of a specified value in a
string
lastIndexOf()
Returns the position of the last found occurrence of a specified value in a
string
localeCompare() Compares two strings in the current locale
replace() Searches a string for a value and returns a new string with the value
search() Searches a string for a value and returns the position of the match
split() Splits a string into an array of substrings
toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale
toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale
toLowerCase() Converts a string to lowercase letters
toString() Returns the value of a String object
toUpperCase() Converts a string to uppercase letters
trim() Removes whitespace from both ends of a string
valueOf() Returns the primitive value of a String object
2015 @ Sonia Sousa 41
JavaScript Numbers
• toString() Method
– returns a number as a string
var x = 123;
x.toString();
// returns 123 from variable x
(123).toString();
// returns 123 from literal 123
(100 + 23).toString();
// returns 123 from expression 100 + 23
2015 @ Sonia Sousa 42
JavaScript Math Object
• Allows you to perform mathematical tasks.
Math.random(); // returns a random number
Math.min() Math.max()
Math.random()
Math.round()
2015 @ Sonia Sousa 43
JavaScript Dates
• lets you work with dates
– Date()
– Date(milliseconds)
– Date(dateString)
– Date(year, month, day, hours, minutes, seconds,
milliseconds)
<script>
var d = new Date();
document.getElementById("demo").innerHTML = d;
</script>
2015 @ Sonia Sousa 44
Date and time Methods
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
setDate() Set the day as a number (1-31)
setFullYear() Set the year (optionally month and day)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)
2015 @ Sonia Sousa 45
JavaScript Output
• Display Possibilities
– window.alert()
– document.write()
– innerHTML
– console.log()
2015 @ Sonia Sousa 46
window.alert()
• Is used to display data as a window alert
<script>
window.alert(5 + 6);
</script>
2015 @ Sonia Sousa 47
document.write()
• For writing information in the document
– Useful for testing purposes or to replace information
in a HTML page
</script>
document.write("<h2>“your name” </h2>");
document.write("<img src='me.jpg' width='180'>");
</script>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 +
6)">Try it</button>
2015 @ Sonia Sousa 48
innerHTML
• To access an HTML element by using
– the document.getElementById(id) method.
• id attribute defines the HTML element
• innerHTML property defines the HTML
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML
="<h3>Welcome</h3>";
</script>
2015 @ Sonia Sousa 49
JS and HTML
• Finding HTML elements
– by id
– by Tag Name
– by Class Name
• Changing elements in HTML
– Write in html
– HTML Content
– Value of an Attribute
document.getElementById("intro");
getElementsByTagName("p");
document.getElementsByClassName("intro");
document.write( );
document.getElementById("p1").innerHTML="New text!";
document.getElementById("image").src="landscape.jpg";
2015 @ Sonia Sousa 50
JS and CSS
• Changing HTML Style
document.getElementById("p2").style.color="blue";
document.getElementById("p2"). background.color="blue";
document.getElementById("demo").innerHTML="<h3>Welcome</h3>";
2015 @ Sonia Sousa 51
Js and events
• When an element is clicked on
• Onclick
• onSubmit
– Or reacting to an event
• onmouseover and onmouseout
2015 @ Sonia Sousa 52
Window Object Methods
Method Description
alert() Displays an alert box with a message and an OK button
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
createPopu
p() Creates a pop-up window
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scroll() Deprecated. This method has been replaced by the scrollTo() method.
scrollBy() Scrolls the document by the specified number of pixels
scrollTo() Scrolls the document to the specified coordinates
stop() Stops the window from loading
2015 @ Sonia Sousa 53
Conditionals
• If , if else, else if
– Execute the code if a specified condition is true
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
2015 @ Sonia Sousa 54
Logic of an if-else statement
condition
evaluated
statement1
true false
statement2
552015 @ Sonia Sousa
Conditionals
• Switch – Case
– perform different actions based on different
conditions.
switch ( expression )
{
case value1 :
statement-list1;
break;
case value2 :
statement-list2;
Break;
case ...
default:
break;
}
switch
and
case
are
reserved
words
If expression
matches value2,
control jumps
to here
2015 @ Sonia Sousa 56
The For Loop
• to run the same code over and over again
– each time with a different value.
for (statement 1; statement 2; statement 3) {
code block to be executed
}
– Statement 1
• is executed before the loop (the code block) starts.
– Statement 2
• defines the condition for running the loop (the code block).
– Statement 3
• is executed each time after the loop (the code block) has been
executed.
2015 @ Sonia Sousa 57
Loops
var i;
for (i = 0; i < 10; i++) {
document.getElementById("demo").innerHTML += i +
"<br>";
}
0
1
2
3
4
5
6
7
8
9
2015 @ Sonia Sousa 58
Conditionals
• If
if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
function timegess()
{
var x="";
var time=new Date().getHours();
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
}
</script>
2015 @ Sonia Sousa 59
Conditionals
• Switch - Case
– More than 1 condition
• select one of many blocks
of code to be executed
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
}
switch (d)
{
case 0:
x="Today it's Sunday";
break;
case 1:
x="Today it's Monday";
break;
case 2:
x="Today it's Tuesday";
break;
case 3:
x="Today it's Wednesday";
break;
case 4:
x="Today it's Thursday";
break;
case 5:
x="Today it's Friday";
break;
case 6:
x="Today it's Saturday";
break;
}
2015 @ Sonia Sousa 60
JavaScript Form Validation
• A form can be validated using JavaScript
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
<form name="myForm" action="demo_form.asp" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
2015 @ Sonia Sousa 61
EXERCISE 3 – JAVASCRIPT
2015 @ Sonia Sousa 62

Mais conteúdo relacionado

Mais procurados

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 

Mais procurados (18)

Modern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial DatabasesModern SQL in Open Source and Commercial Databases
Modern SQL in Open Source and Commercial Databases
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Xml schema
Xml schemaXml schema
Xml schema
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented Programming
 
Ruby objects
Ruby objectsRuby objects
Ruby objects
 
PHP- Introduction to Object Oriented PHP
PHP-  Introduction to Object Oriented PHPPHP-  Introduction to Object Oriented PHP
PHP- Introduction to Object Oriented PHP
 
Java2
Java2Java2
Java2
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
J query lecture 1
J query lecture 1J query lecture 1
J query lecture 1
 
Java
JavaJava
Java
 
Software Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-iSoftware Engineering Lec5 oop-uml-i
Software Engineering Lec5 oop-uml-i
 
XML's validation - XML Schema
XML's validation - XML SchemaXML's validation - XML Schema
XML's validation - XML Schema
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards09 Object Oriented Programming in PHP #burningkeyboards
09 Object Oriented Programming in PHP #burningkeyboards
 
Java Introduction Workshop Day 2
Java Introduction Workshop Day 2 Java Introduction Workshop Day 2
Java Introduction Workshop Day 2
 
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and ObjectJava OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 3) - Class and Object
 
Absolutely Typical - The whole story on Types and how they power PL/SQL Inter...
Absolutely Typical - The whole story on Types and how they power PL/SQL Inter...Absolutely Typical - The whole story on Types and how they power PL/SQL Inter...
Absolutely Typical - The whole story on Types and how they power PL/SQL Inter...
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
 

Destaque

Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2
Sónia
 
A key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsA key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactions
Sónia
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2
Sónia
 
Technology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point FinalTechnology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point Final
jhustad1
 

Destaque (20)

Nettets genkomst?
Nettets genkomst?Nettets genkomst?
Nettets genkomst?
 
Helping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviewsHelping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviews
 
Ifi7184 lesson4
Ifi7184 lesson4Ifi7184 lesson4
Ifi7184 lesson4
 
Ifi7174 lesson4
Ifi7174 lesson4Ifi7174 lesson4
Ifi7174 lesson4
 
Literature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer ScienceLiterature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer Science
 
My ph.d Defence
My ph.d DefenceMy ph.d Defence
My ph.d Defence
 
Ifi7174 lesson1
Ifi7174 lesson1Ifi7174 lesson1
Ifi7174 lesson1
 
Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective
 
Technology, Trust, & Transparency
Technology, Trust, & TransparencyTechnology, Trust, & Transparency
Technology, Trust, & Transparency
 
Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2
 
A key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsA key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactions
 
Ifi7184 lesson5
Ifi7184 lesson5Ifi7184 lesson5
Ifi7184 lesson5
 
Lesson 17
Lesson 17Lesson 17
Lesson 17
 
Trust workshop
Trust workshopTrust workshop
Trust workshop
 
Ifi7184 lesson6
Ifi7184 lesson6Ifi7184 lesson6
Ifi7184 lesson6
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2
 
Technology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point FinalTechnology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point Final
 
A design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignA design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction Design
 
Workshop 1
Workshop 1Workshop 1
Workshop 1
 
MG673 - Session 1
MG673 - Session 1MG673 - Session 1
MG673 - Session 1
 

Semelhante a Ifi7174 lesson3

Lect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptxLect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptx
zainm7032
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
Mark Rackley
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
Fabrizio Giudici
 

Semelhante a Ifi7174 lesson3 (20)

SEF2013 - A jQuery Primer for SharePoint
SEF2013 - A jQuery Primer for SharePointSEF2013 - A jQuery Primer for SharePoint
SEF2013 - A jQuery Primer for SharePoint
 
Lect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptxLect-5--JavaScript-Intro-12032024-105816am.pptx
Lect-5--JavaScript-Intro-12032024-105816am.pptx
 
Getting Started with Javascript
Getting Started with JavascriptGetting Started with Javascript
Getting Started with Javascript
 
Java script
Java scriptJava script
Java script
 
SPSDenver - SharePoint & jQuery - What I wish I would have known
SPSDenver - SharePoint & jQuery - What I wish I would have knownSPSDenver - SharePoint & jQuery - What I wish I would have known
SPSDenver - SharePoint & jQuery - What I wish I would have known
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
Java script
Java scriptJava script
Java script
 
FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1FFW Gabrovo PMG - JavaScript 1
FFW Gabrovo PMG - JavaScript 1
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Java script
Java scriptJava script
Java script
 
SharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentialsSharePoint Cincy 2012 - jQuery essentials
SharePoint Cincy 2012 - jQuery essentials
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript
JavaScriptJavaScript
JavaScript
 
2012 - HTML5, CSS3 and jQuery with SharePoint 2010
2012 - HTML5, CSS3 and jQuery with SharePoint 20102012 - HTML5, CSS3 and jQuery with SharePoint 2010
2012 - HTML5, CSS3 and jQuery with SharePoint 2010
 
Object(ive) Thinking
Object(ive) ThinkingObject(ive) Thinking
Object(ive) Thinking
 
SPSTC - SharePoint & jQuery Essentials
SPSTC - SharePoint & jQuery EssentialsSPSTC - SharePoint & jQuery Essentials
SPSTC - SharePoint & jQuery Essentials
 
Rich Internet Applications con JavaFX e NetBeans
Rich Internet Applications  con JavaFX e NetBeans Rich Internet Applications  con JavaFX e NetBeans
Rich Internet Applications con JavaFX e NetBeans
 
TypeScript and SharePoint Framework
TypeScript and SharePoint FrameworkTypeScript and SharePoint Framework
TypeScript and SharePoint Framework
 
JavaScript front end performance optimizations
JavaScript front end performance optimizationsJavaScript front end performance optimizations
JavaScript front end performance optimizations
 
SQL Server Managing Test Data & Stress Testing January 2011
SQL Server Managing Test Data & Stress Testing January 2011SQL Server Managing Test Data & Stress Testing January 2011
SQL Server Managing Test Data & Stress Testing January 2011
 

Mais de Sónia

Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)
Sónia
 
20 06-2014
20 06-201420 06-2014
20 06-2014
Sónia
 
Ifi7155 project-final
Ifi7155 project-finalIfi7155 project-final
Ifi7155 project-final
Sónia
 

Mais de Sónia (15)

MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)
 
Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Ifi7184.DT lesson 2
Ifi7184.DT lesson 2
 
IFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesIFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languages
 
IFI7184.DT about the course
IFI7184.DT about the courseIFI7184.DT about the course
IFI7184.DT about the course
 
Comparative evaluation
Comparative evaluationComparative evaluation
Comparative evaluation
 
Ifi7155 Contextualization
Ifi7155 ContextualizationIfi7155 Contextualization
Ifi7155 Contextualization
 
Hcc lesson7
Hcc lesson7Hcc lesson7
Hcc lesson7
 
Hcc lesson6
Hcc lesson6Hcc lesson6
Hcc lesson6
 
eduHcc lesson2-3
eduHcc lesson2-3eduHcc lesson2-3
eduHcc lesson2-3
 
Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)
 
20 06-2014
20 06-201420 06-2014
20 06-2014
 
Ifi7155 project-final
Ifi7155 project-finalIfi7155 project-final
Ifi7155 project-final
 
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
 
Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)
 
Workshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluationWorkshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluation
 

Último

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Último (20)

SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

Ifi7174 lesson3

  • 1. IFI7174.DT – Lesson 3 JavaScript
  • 2. JavaScript • Is a lightweight – Object Oriented Programming (OOP) language • Why JavaScript? – It helps you to add behaviors into your webpages – It changes HTML Content – It changes HTML Styles (CSS) 2015 @ Sonia Sousa 2
  • 3. JavaScript • Is typically used in browsers – to power dynamic websites. • add functionality; • validate input, and • communicate with web servers • JS code is loaded and ran – Inline within HTML code <script> tags – In blocks • <script> JS code </script> 2015 @ Sonia Sousa 3
  • 4. JavaScript • Can be: – Load as an external scripts • External – Inline within HTML code <script> tags – Embedded • <head> – functions • <body> – event change <script src="myScript.js"></script> <script>document.write("<h1>Hello, there!</h1>"); </script> <head> <title>Embedded JS Example</title> <script> document.write("Oops"); </script> </head> 2015 @ Sonia Sousa 4
  • 5. External JS Advantages • It separates HTML and code • It makes HTML and JavaScript easier to read and maintain • Cached JavaScript files can speed up page loads 2015 @ Sonia Sousa 5
  • 6. JS Embedded in HTML <script> function myFunction() { document.write("Oops! The document disappeared!"); } </script> <button onclick="myFunction()">Try it</button> • <head> </head> • <body> </body> 2015 @ Sonia Sousa 6
  • 7. JS inline with HTML <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <button type="button" onclick="myFunction()">Try it</button> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> 2015 @ Sonia Sousa 7 • <body> </body>
  • 8. The Document Object • When an HTML document is loaded into a web browser, – it becomes a document object. • The document object – provides properties and methods • to access all node objects, from within JavaScript – represents • the root node of the HTML document – It controls the • element, text, attribute, and comment nodes 2015 @ Sonia Sousa 8
  • 9. Document Object Model (DOM) • starts by… 1. browser window itself 2. document page, 3. the elements included on the page; and 4. their attributes. Source: Wikipedia The object hierarchy 2015 @ Sonia Sousa 9
  • 10. How JS and the DOM cooperate • When a web page is loaded, – The browser creates a DOM of the page • Like a tree Source: w3schools2015 @ Sonia Sousa 10
  • 11. DOM Window documen t meta Textbox Radio button head body form[] link Imagestitle div ul li Establish the Order of things 2015 @ Sonia Sousa 11
  • 12. How JS and the DOM cooperate • JavaScript can change – the HTML elements in the page – the HTML attributes in the page – the CSS styles in the page • JavaScript can react to – the events in the page • This is done by – object notation 2015 @ Sonia Sousa 12
  • 13. Object notation • Access to elements – be referenced using dot notation • starting with the highest-level object – (i.e., window). » But as the window is in the top hierarchy do not need to be refereed – Objects can be referred to • by name; or id; or by their position on the page document.getElementById("demo").innerHTML = "Hello JavaScript”; 2015 @ Sonia Sousa 13
  • 14. JavaScript Syntax • Basic rules – Ends with ; (semi-colons) – ! is case sensitive ! • Comments – double slash (//) • 1 line comment – between /* and */ • More than 1 line comment 2015 @ Sonia Sousa 14
  • 15. JS programs • A program is a – list of "instructions” to be "executed" by the computer – These instructions are called statements • JS statements are separated by semicolons ; • A statement composed of: – Values, Operators, Expressions, Keywords, and Comments. 2015 @ Sonia Sousa 15
  • 16. JavaScript statements • Statements includes – Values, Operators, Expressions, Keywords, and Comments – Values are • Literal or variables – Functions are • a block of code that can execute some action – Events are • actions triggered by someone 2015 @ Sonia Sousa 16
  • 17. Values • Literal values are – Numbers • with or without decimals (10.50 or 1001) – Strings • Double or single quotes ("John Doe” ‘John Doe’) – Variables • Are used to store data (var x; x = 6;) 2015 @ Sonia Sousa 17
  • 18. JS Keywords • To identify the JavaScript action to be performed. Keyword Description break Terminates a switch or a loop continue Jumps out of a loop and starts at the top do ... while Executes a block of statements, and repeats the block, while a condition is true for Marks a block of statements to be executed, as long as a condition is true function Declares a function if ... else Marks a block of statements to be executed, depending on a condition return Exits a function switch Marks a block of statements to be executed, depending on different cases try ... catch Implements error handling to a block of statements var Declares a variable 2015 @ Sonia Sousa 18
  • 19. JS Statements • A statement is the line of code that tell – the browser to execute something document.getElementById("demo").innerHTML = "Hello!"; • JavaScript statements Var x = 5; var y = 6; var z = x + y; document.getElementById("demo").innerHTML = z; 2015 @ Sonia Sousa 19
  • 20. JavaScript Statements • Giving a command to the browser <script> function myFunction() { document.write("Oops! The document disappeared!"); } </script> <button onclick="myFunction()">Try it</button> <script> function myFunction() { document.write("Oops! The document disappeared!"); } </script> 2015 @ Sonia Sousa 20
  • 21. JS code and Blocks JS code blocks JS functions <script> function myFunction() { document.write("Oops! The document disappeared!"); } </script> <script> 1. document.write("<h1>Hello, there!</h1>"); 2. document.getElementById("demo").innerHTML="Hello Dolly"; 3. document.getElementById("myDIV").innerHTML="How are you?”; </script> • Define statements to be executed together • JavaScript functions are statements grouped in blocks 2015 @ Sonia Sousa 21
  • 22. JS and HTML Styles (CSS) • JavaScript can change – HTML elements – (CSS) Styles – Or validate input (data) • Using methods, conditional and fuctions • For instance, to change the text – It uses getElementById() method document.getElementById("demo").innerHTML = "Hello JavaScript”; 2015 @ Sonia Sousa 22
  • 23. JavaScript Variables • variables are "containers" of information – We can name it using letters (like x) • The variable can contain – Letter, numerical values or expressions var x=5; var y=6; var z=x+y; "declaring" a variable assign a value var carname; carname="Volvo"; 2015 @ Sonia Sousa 23
  • 24. Declaring (Creating) JS Variables • Primitive data types – Number var x = 5; – String var carname = “Volvo XC60"; – Boolean var x = true; var y = false; 2015 @ Sonia Sousa 24
  • 25. Declaring (Creating) JS Variables • JS Array var cars=new Array(); cars[0]="Saab"; cars[1]="Volvo"; cars[2]="BMW"; var cars = ["Saab", "Volvo", "BMW"]; • JavaScript Objects var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; 2015 @ Sonia Sousa 25
  • 26. Object (Properties and Methods) • data (variables) as objects – they have properties – they have methods Object Properties Methods Car car.name = Fiat car.model = 500 car.weight = 850kg car.color = white car.start() car.drive() car.brake() 2015 @ Sonia Sousa 26
  • 27. JS Operators • Operators are used to – assign values to variables using (=) • var x = 5; var y = 6; • Arithmetic operators • Comparison operators • Logical operators Operator Description + Addition - Subtraction * Multiplication / Division % Modulus ++ Increment -- Decrement 2015 @ Sonia Sousa 27
  • 28. JS Operators Opera tors example results + x=y+2 Addition x=7 - x=y-2 Subtraction x=3 * x=y*2 Multiplication x=10 / x=y/2 Division x=2.5 ++ x=++y Increment x=6 -- x=--y Decrement x=4 == x==8 equal to false != x!=8 Not equal to true > x>8 greater than false < x<8 less than true >= x>=8 greater than or equal to false <= x<=8 Less tan or equal to true && (x < 10 && y > 1) and true || (x==5 || y==5) or false ! !(x==y) not true Logical Comparison Arithmetic 2015 @ Sonia Sousa 28
  • 29. Assignment Operators Operator Example Same as Resul t = x=y += x+=y x=x+y -= x-=y x=y-2 *= x*=y x=x*y ++ x=++y Increment x=6 -- x=--y Decrement x=4 == x==8 != x!=8 > x>8 < x<8 >= x>=8 <= x<=8 && (x < 10 && y > 1) || (x==5 || y==5) ! !(x==y) 2015 @ Sonia Sousa 29
  • 30. JS Expressions • Combine values, variables, and operators – The computation is called an evaluation • 5 * 10 evaluates to 50 – can also contain variable values • x * 10 • "John" + " " + "Doe" 2015 @ Sonia Sousa 30
  • 31. JavaScript Functions • is a block of code designed to perform a particular task. – A JavaScript function is executed when "something" invokes it (calls it). function name(parameter1, parameter2, parameter3) { code to be executed } 2015 @ Sonia Sousa 31
  • 32. Function Syntax function name(parameter1, parameter2, parameter3) { code to be executed } <!DOCTYPE html> <html> <head> <script> function myFunction() { alert("Hello World!"); } </script> </head> <body> <button onclick="myFunction()”> Try it </button> </body> </html> Function name Code to execute Call function 2015 @ Sonia Sousa 32
  • 33. Function Invocation • The code inside the function will execute when "something” happens – an event occurs (when a user clicks a button) – it is invoked (called) from JavaScript code – Automatically (self-invoked) 2015 @ Sonia Sousa 33
  • 34. JavaScript Functions • A block of code that will be executed when "someone" calls it <script> function myFunction() { document.write("Oops! The document disappeared!"); } </script> <button onclick="myFunction()">Try it</button> <script> function myFunction() { document.write("Oops! The document disappeared!"); } </script> Code Block Call function 2015 @ Sonia Sousa 34
  • 35. Return values • Functions often compute a return value. var x = myFunction(4, 3); // Function is called, return value will end up in x function myFunction(a, b) { return a * b; // Function returns the product of a and b } 2015 @ Sonia Sousa 35
  • 36. Function with Arguments </head> <body> <button onclick="myFunction()">Try it</button> <button onclick="myFunction('Bob','Builder')">Try it</button> <script> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script> 2015 @ Sonia Sousa 36 <script> myFunction(argument1,argument2) { some code } </script>
  • 37. Using ID with function </head> <body> <p id="demo"></p> <script> document.getElementById("demo").innerHTML=myFunction(4,3); </script> <script> function myFunction(a,b) { return a*b; } </script> 2015 @ Sonia Sousa 37 <script> myFunction(argument1,argument2) { some code } </script>
  • 38. JavaScript Events • Is something the browser does, or something a user does – Event handlers • used to handle, and verify, user input, user actions, and browser actions. – HTML events • An HTML web page has finished loading • An HTML input field was changed • An HTML button was clicked <some-HTML-element some-event="some JavaScript"> <button onclick="this.innerHTML=Date()">The time is? </button> 2015 @ Sonia Sousa 38
  • 39. HTML DOM Events Event Description onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page onmouseenter occurs when the pointer is moved onto an element onmousedown the user presses a mouse button over an element 2015 @ Sonia Sousa 39
  • 40. JavaScript Strings • String have Properties and Methods – Primitive value • var firstName = "John” var x = "John"; – String objects • var firstName = new String("John") var y = new String("John"); 2015 @ Sonia Sousa 40
  • 41. JavaScript Strings Method Description charAt() Returns the character at the specified index (position) concat() Joins two or more strings, and returns a copy of the joined strings indexOf() Returns the position of the first found occurrence of a specified value in a string lastIndexOf() Returns the position of the last found occurrence of a specified value in a string localeCompare() Compares two strings in the current locale replace() Searches a string for a value and returns a new string with the value search() Searches a string for a value and returns the position of the match split() Splits a string into an array of substrings toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale toLowerCase() Converts a string to lowercase letters toString() Returns the value of a String object toUpperCase() Converts a string to uppercase letters trim() Removes whitespace from both ends of a string valueOf() Returns the primitive value of a String object 2015 @ Sonia Sousa 41
  • 42. JavaScript Numbers • toString() Method – returns a number as a string var x = 123; x.toString(); // returns 123 from variable x (123).toString(); // returns 123 from literal 123 (100 + 23).toString(); // returns 123 from expression 100 + 23 2015 @ Sonia Sousa 42
  • 43. JavaScript Math Object • Allows you to perform mathematical tasks. Math.random(); // returns a random number Math.min() Math.max() Math.random() Math.round() 2015 @ Sonia Sousa 43
  • 44. JavaScript Dates • lets you work with dates – Date() – Date(milliseconds) – Date(dateString) – Date(year, month, day, hours, minutes, seconds, milliseconds) <script> var d = new Date(); document.getElementById("demo").innerHTML = d; </script> 2015 @ Sonia Sousa 44
  • 45. Date and time Methods Method Description getDate() Get the day as a number (1-31) getDay() Get the weekday as a number (0-6) getFullYear() Get the four digit year (yyyy) getHours() Get the hour (0-23) getMilliseconds() Get the milliseconds (0-999) getMinutes() Get the minutes (0-59) getMonth() Get the month (0-11) getSeconds() Get the seconds (0-59) getTime() Get the time (milliseconds since January 1, 1970) setDate() Set the day as a number (1-31) setFullYear() Set the year (optionally month and day) setHours() Set the hour (0-23) setMilliseconds() Set the milliseconds (0-999) setMinutes() Set the minutes (0-59) setMonth() Set the month (0-11) setSeconds() Set the seconds (0-59) setTime() Set the time (milliseconds since January 1, 1970) 2015 @ Sonia Sousa 45
  • 46. JavaScript Output • Display Possibilities – window.alert() – document.write() – innerHTML – console.log() 2015 @ Sonia Sousa 46
  • 47. window.alert() • Is used to display data as a window alert <script> window.alert(5 + 6); </script> 2015 @ Sonia Sousa 47
  • 48. document.write() • For writing information in the document – Useful for testing purposes or to replace information in a HTML page </script> document.write("<h2>“your name” </h2>"); document.write("<img src='me.jpg' width='180'>"); </script> <p>My first paragraph.</p> <button type="button" onclick="document.write(5 + 6)">Try it</button> 2015 @ Sonia Sousa 48
  • 49. innerHTML • To access an HTML element by using – the document.getElementById(id) method. • id attribute defines the HTML element • innerHTML property defines the HTML <p>My First Paragraph</p> <p id="demo"></p> <script> document.getElementById("demo").innerHTML ="<h3>Welcome</h3>"; </script> 2015 @ Sonia Sousa 49
  • 50. JS and HTML • Finding HTML elements – by id – by Tag Name – by Class Name • Changing elements in HTML – Write in html – HTML Content – Value of an Attribute document.getElementById("intro"); getElementsByTagName("p"); document.getElementsByClassName("intro"); document.write( ); document.getElementById("p1").innerHTML="New text!"; document.getElementById("image").src="landscape.jpg"; 2015 @ Sonia Sousa 50
  • 51. JS and CSS • Changing HTML Style document.getElementById("p2").style.color="blue"; document.getElementById("p2"). background.color="blue"; document.getElementById("demo").innerHTML="<h3>Welcome</h3>"; 2015 @ Sonia Sousa 51
  • 52. Js and events • When an element is clicked on • Onclick • onSubmit – Or reacting to an event • onmouseover and onmouseout 2015 @ Sonia Sousa 52
  • 53. Window Object Methods Method Description alert() Displays an alert box with a message and an OK button close() Closes the current window confirm() Displays a dialog box with a message and an OK and a Cancel button createPopu p() Creates a pop-up window moveBy() Moves a window relative to its current position moveTo() Moves a window to the specified position open() Opens a new browser window print() Prints the content of the current window prompt() Displays a dialog box that prompts the visitor for input resizeBy() Resizes the window by the specified pixels resizeTo() Resizes the window to the specified width and height scroll() Deprecated. This method has been replaced by the scrollTo() method. scrollBy() Scrolls the document by the specified number of pixels scrollTo() Scrolls the document to the specified coordinates stop() Stops the window from loading 2015 @ Sonia Sousa 53
  • 54. Conditionals • If , if else, else if – Execute the code if a specified condition is true if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false } 2015 @ Sonia Sousa 54
  • 55. Logic of an if-else statement condition evaluated statement1 true false statement2 552015 @ Sonia Sousa
  • 56. Conditionals • Switch – Case – perform different actions based on different conditions. switch ( expression ) { case value1 : statement-list1; break; case value2 : statement-list2; Break; case ... default: break; } switch and case are reserved words If expression matches value2, control jumps to here 2015 @ Sonia Sousa 56
  • 57. The For Loop • to run the same code over and over again – each time with a different value. for (statement 1; statement 2; statement 3) { code block to be executed } – Statement 1 • is executed before the loop (the code block) starts. – Statement 2 • defines the condition for running the loop (the code block). – Statement 3 • is executed each time after the loop (the code block) has been executed. 2015 @ Sonia Sousa 57
  • 58. Loops var i; for (i = 0; i < 10; i++) { document.getElementById("demo").innerHTML += i + "<br>"; } 0 1 2 3 4 5 6 7 8 9 2015 @ Sonia Sousa 58
  • 59. Conditionals • If if (time<20) { x="Good day"; } else { x="Good evening"; } function timegess() { var x=""; var time=new Date().getHours(); if (time<10) { x="Good morning"; } else if (time<20) { x="Good day"; } else { x="Good evening"; } } </script> 2015 @ Sonia Sousa 59
  • 60. Conditionals • Switch - Case – More than 1 condition • select one of many blocks of code to be executed 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 } switch (d) { case 0: x="Today it's Sunday"; break; case 1: x="Today it's Monday"; break; case 2: x="Today it's Tuesday"; break; case 3: x="Today it's Wednesday"; break; case 4: x="Today it's Thursday"; break; case 5: x="Today it's Friday"; break; case 6: x="Today it's Saturday"; break; } 2015 @ Sonia Sousa 60
  • 61. JavaScript Form Validation • A form can be validated using JavaScript function validateForm() { var x = document.forms["myForm"]["fname"].value; if (x == null || x == "") { alert("Name must be filled out"); return false; } } <form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> 2015 @ Sonia Sousa 61
  • 62. EXERCISE 3 – JAVASCRIPT 2015 @ Sonia Sousa 62