Unit 20 - Client Side Customisation of Web Pages Week 4 – Lesson 5 Fundamentals of Scripting
Unit 20 - Client Side
Customisation of Web Pages
Week 4 – Lesson 5
Fundamentals of Scripting
The story so far...
• three methods of writing CSS:
– In-line
– Embedded }These are sometimes called
– External }’block’ methods – all the CSS is
blocked together.
• The CSS Box model
• Positioning
• Designed a website (almost)
Fundamentals of Scripting
Languages• What a scripting language is
• How it works
• What types are available
• The main features
• How does a scripting language improve
functionality
• Explain in detail how a browser
implements a scripting language
Fundamentals of Scripting
Languages
• Characteristics of scripting languages:
• Uses of a scripting language:
• Scripting language constructs:
Characteristics of scripting
languagesnature of language eg
– object oriented,
• objects;
• methods;
• Properties;
– event driven;
• handling events;
hiding scripts;
security issues eg
• reading,
• writing,
• client files,
• opening/closing user windows,
• reading information;
including scripts inside HTML
Introduction
• Find definitions for the following terms:
– Interactivity
– Static website
– Dynamic website
– Interpret
– Go live
• Name some scripting languages.
5 minute task
Characterisitics
• Type of language
• Hiding scripts from older browsers
• Security issues
• Including scripts inside HTML
A snippet of code...
• <html>
• <head>
• <script>
• This is where the scripting language would be
written.
• </script>
• </head>
• <body>Lorem ipsum</body>
• </html>
Types of Scripting Language
2 modes of operation
• Event-driven
• Object-oriented
Write a brief description of each.
Include relevant webpage examples of each
mode.
5 minute task
Types
• Object Oriented
– Code broken into
• Objects– Self-contained
modules
– Knows about itself
– Knows what it can do
– Knows what it can
interact with
• Event driven
• Code broken into
• Events• Code is triggered
when actions occur:
• Mouse click
• Key press
• Movement
• Transmission of data
Objects
•A type of data which:
•Knows things about itself (properties)
•Knows how to do things (methods)
•Many objects already exist
•Can create new ones
An example of ‘object’ code...
• The ‘String’ object:
• Dot operator
<script>
Hw=“Hello World”
document.write(Hw.length)
</script>
Methods
• Each object knows which methods it can
carry out, eg (string object):
• <script>
• Hw=“Hello world”
• document.write(Hw.toUpperCase())
• </Script>
• Copy this code and observe the screen
output.
Methods
• A method is an action which can be
performed by an object
• <html>
<body>
<script type="text/vbscript">
document.write("<h1>Hello World!</h1>")
</script>
</body>
</html>
Methods
• The properties of an object may change as a result of a
method being carried out.
• There are several preset objects each with predefined
methods:
.write display information
.click simulate a click
.value take the value from an input
.open loads a page in a new browser window
.selectedIndex shows which option from a drop-down list has been
selected
Object-oriented example
• Dot operator
• E.g.
<script>
For (count = 0; count <= 5; count++)
{document.write(“The number is “ + count)
Document. Write(“<br>”)//uses html within
script}
</script>
Event-driven example
• Often associated with functions (event-
handling)
• Function is called in body of page
• Function names are case-sensitive
Event-driven example
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
Older browsers
• May not support scripts
• Need to hide the script to avoid confusion
• Put the script within HTML comments
• <script>
• <!--
• script code written here
• //--!>
• </script>
Security
• Scripts are executed on the clients PC
• Entry point for hackers
• Makes both client and website vulnerable
• Website owners (if unscrupulous) could
also take advantage and read client’s PC
– eg data-mining or reading other browser
windows
What law attempts to control this?
Security
• Major issue is placing code to run on
client’s machine
• Cross-site scripting attacks (XSS)
• Vulnerability present in about 70% of web
applications (sources, Veracode, Acunetix)
http://www.veracode.com/security/xss
http://www.acunetix.com/websitesecurity/cro
ss-site-scripting/ (accessed 10/11/17)
Security
• http://www.acunetix.com/websitesecurity/cross-site-scripting/
XSS
• Reflective XSS– Malicious Javascript in e-mail, victim clicks link,
Javascript sent to vulnerable website, reflected back
and run on victim machine.
http://www.veracode.com/security/xss
More XSS
• Persistent attack• Attacker includes malicious script as part of user-name,
other users view profile, code executes on other users
machine
http://www.veracode.com/security/xss
Uses of scripting language
• To provide interactivity.
– Interactivity – 2-way communication between
human and computer
Uses of scripting language
• To provide interactivity.
– You will need to include 3 different
interactivities in your website later in this unit.
– What examples can you find?
– Find at least 5 different interactivities now.
– Reference the URLs
– Can you find the scripts which run these
interactivities? 10 minute task
Uses of scripting language
• To provide interactivity.
– Alerts (pop-ups)
– Prompts and confirmation of choices
– Checking/validating input
– Handling forms
– Redirecting
– Rollover buttons
– Browser detection
– Cookies – installing and maintaining
Designing interactivities
• For your website you must design
interactivities.
• To do this you should use:
– Pseudo-code
– Flow diagrams
Pseudo code
• Code but not code …
Pseudo Code JavaScript
Age=input from user
If age +> 18
then print onscreen
“I am an adult”
Else
Print onscreen “I am x years old”
Age=prompt(“Enter age”,””);
If (age>=18)
{document.write(“I am an
adult”);}
Else
{document.write(“I am “+ age +”
years old”);}
Flow diagram
Input age
Is user
>=18?
yes
No I am x years
old
I am an adult
Design task
• Refer to two (or more) of the interactivities
you previously discovered.
• Create a design for each using:
– Pseudo code
– Flow diagram
Scripting language constructs
• syntax eg
• dot operator,
• values,
• variables,
• operators,
• assignment,
• comparisons;
• methods eg
• write(),
• click(),
• open(),
• selected();
• properties eg
• name,
• width,
• ID,
• value
• loops eg
• for,
• for/in,
• do/while;
• decision making eg
• if,
• if/else,
• switch/case;
• functions (calling, parameter
passing);
• handling events eg
• onfocus,
• onload,
• onblur,
• onmouseover;
Constructs
• Need correct construction:
– Syntax i.e. Grammar and order correct of
words
• Dot operator allows an object to use a method
– Variable data stored as text or numbers
• Must have unique name within script
– Loops or iterations code which is executed
repeatedly.
The maths bit
• Often need calculations within a script,
valid operators include:
• + plus - minus
• * multiply / divide
• > greater than < less than
• ++ increment by 1 -- decrement by 1
• == checks if equal != not equal
• >= equal to or less than
Loops
• Or iterations
• Code which is executed repeatedly until
preset condition is met
• Condition is set either at end or start of
code
• Actions are defined in {curly brackets}
• Different types producing different effects
Loops
• for - loops through a block of code a
specified number of times
• while - loops through a block of code
while a specified condition is true
• do...while - also loops through a block of
code while a specified condition is true
• for...in - loops through the properties of an
object
Loop example
• <script>
• For (count = 0; count <= 5; count++)
• {document.write(“The number is “ + count)
• Document. Write(“<br>”)//uses html within
script}
• </script>
Scripting exercises
• A FOR loop to be executed while count is
less than or equal to five.
• A FOR/in loop to be executed through an
array.
• A WHILE loop to be executed while count
is less than 5
• Hint: Studshare\BTEC\Level 3\Lesson 4..
Loop example (for/in)
• <script>
• Numbers = new Array()
• Numbers [0] = “zero”
• Numbers [1] = “one”
• Numbers [2] = “two”
• For (x in numbers)
• { document.write (“The number is “ + numbers
[x])
• Document.write(“<br>”)}
• </script>
Loop example (while)
• <script>
• Count = 0
• While (count <= 5)
• { document.write(“The number is “ + count)
• Document.write(“<br>”)
• Count ++
• }
• </script>
Playing with loops
• Break - breaks the loop and continue
executing the code that follows after the
loop (if any).
• Continue - breaks the iteration and
continues with the next value.
Break example
• for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The number is " + i + "<br />";
}
continue
• for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
x=x + "The number is " + i + "<br />";
}
Loops
• for
• while
• for…in
• break
• continue
Task
• Find or create an example of a loop –
there may be one in one of the
interactivities you discovered earlier.
• Record this – you will need it for the
assignment
Dot operator
– <script>
– Str=“first message”
1. Document.write(str.replace(/first/,”second”))
– </script>
– Object ‘string’ uses the method ‘replace’
• Hw = “Hello world”
1. Document.write(hw.length)
2. Document.write(hw.toUpperCase()
These constructs are nearly right;
nearly right doesn’t work, can you
correct them?
Variables
• A way of storing data (e.g.text or numbers)
• Must have a unique name within script
• Names cannot contain spaces
• Names cannot start with a number
• Should be meaningful for editing
• Can be assigned a value (initial data)
• Collection of variables can be stored in an array
• Array should be named and each item
numbered (starting with 0)
Turnip array
• <html>
• <head>
• <script>
• product_name="turnip"
• quantity=50
• </script>
• </head>
• <body>
• <script>
• document.write (product_name, ("<br>"), quantity)
• </script>
• </body>
• </html>
Veg Turnip carrot spinach celery cabbage
Array_1
• var vegetables= new Array(5)
• vegetables["turnip"]= "50";
• vegetables["carrot"]= 10;
• vegetables["spinach"]= 20;
• vegetables["celery"]= 30 ;
• vegetables["cabbage"]= 1;
• </script>
• <head>
• <body>
As a table
• <script>
• document.write("<table border=\"1\" cellpadding=\"5\">");
• document.write("<tr><th>Veg</th><th>quantity</th></tr>");
• //Now we start the for loop using the variable vegetable to hold our
key.
• for ( var vegetable in vegetables) //print the values into a table cell
for each iteration
• document.write( "<tr><td>" + vegetable + "</td><td>" +
vegetables[vegetable] + "</td></tr>");
• //finally close the table
• document.write ("</table>");
Horizontal table …1
• <script>document.write("<table
border=\"1\"
cellpadding=\"5\">");document.write("<tr><
th>Veg</th>");//Now we start the for loop
using the variable vegetable to hold our
key.for ( var vegetable in vegetables)
//print the values into a table cell for each
iteration on top row document.write("<td>"
+ vegetable + "</td>")</script>
Horizontal table…2
• <script>document.write
("</tr><tr><th>quantity</th>"); //close top
row, start second row for ( var vegetable in
vegetables) //print the values into a table
cell for each iteration, bottom row
document.write ("<td>" +
vegetables[vegetable] + "</td>"); //finally
close the table
• document.write ("</tr></table>"); </script>
Array with Maths
• Using the vegetable array:
• Create functions to change the stock level
depending on user activity. E.g.
• Stock check to see if the correct number of
turnips (50) are present ==
• Adjust stock level because of sales --
• Adjust stock level because of purchases +
• Alarm when less than a certain number
Useful tools
• Firefox add-ons:
– Web-dev
– firebug
Fundamentals of Scripting
Languages• What is a scripting language?
• How does it work?
• What types are available?
• How does a scripting language improve
functionality?
• Explain in detail how a browser
implements a scripting language
Functions
• function functionname()
{
some code
}
Simple alert function
1. <!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
arguments
• Values that are passed along with a function
(also called parameters)
• can be used inside the function.
• You can send as many arguments as you like,
separated by commas (,)
• Declare the variables when you name the
function; must be kept in expected order
• function myFunction(var1,var2)
{
some code
}
Example of arguments
• <button onclick="myFunction('Harry Potter','Wizard')">Try
it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>
• Note how “name” and “job” are kept in the expected order.
• <button onclick="myFunction('Harry Potter','Wizard')">Try
it</button>
<button onclick="myFunction('Bob',‘Lecturer')">Try it</button>
Return values
• return a value back to where the call was
made
• the function will stop executing, and return
the specified value.
Decision making
• Script can be used to make decisions
automatically.
• if
• if…else
• Switch...case
if statement
• Note that if is written in lowercase letters.
Using uppercase letters (IF) will generate
a JavaScript error.
• <script>
• function myFunction() {
• var time = new Date().getHours();
• if (time < 20) {
•
if statement
• document.getElementById("demo").innerH
TML = "Good day";
• }
• }
• </script>
•
• <p>Click the button to display "Good day",
only if the time is less than 20:00.</p>
• <button onclick="myFunction()">Try
it</button>
• <p id="demo"></p>
If…else…
• if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
If…else if…else
• 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
}
Switch example
• Use the switch statement to 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
}
Default
• Use the default keyword to specify what to do if there is no match:
• var day=new Date().getDay();
switch (day)
{
case 6:
x="Today it's Saturday";
break;
case 0:
x="Today it's Sunday";
break;
default:
x="Looking forward to the Weekend";
}
‘Boxes’
• Alert box
• Confirm box
• Prompt box
alert
• <!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="Show alert box"
/>
</body>
</html>
confirm
• var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}
prompt
• used if you want the user to input a value before entering a page.
• the user will have to enter an input value
• the user will have to click either "OK" or "Cancel" to proceed
• If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
• var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
x="Hello " + name + "! How are you today?";
}
Function example
• <html>
• <head>
• <title> Function example </title>
• <script>
• Function details() {
• // insert your new code here
• }
• </script>
• </head>
• <body>
• </body>
• </html>
Function example...After the body tag insert:
• <b> Methods example Page</b>
• <br>
• <form name=“DetailsForm”>
• Enter full name <input type =“text” name=“fullname”><br>
• Gender:
• <select id=gender>
• <option>male</option>
• <option>female</option>
• </select></br>
• <input type = “button” value=“ClickMe onClick=“details()”>
• </form>
Function task
• Save the file as functionexample.html
• Find out the value of name
• Find out which gender has been selected
• Write both to the page so they are
displayed on screen
Function example
• Make your function “details” bring up an
alert box when “ClickMe” is clicked.
• {alert(“Lorem ipsum”);
• }
• Substitute suitable text for “Lorem ipsum”
Function example
Now have your alert box return a value from your input
box along with the text.
Function example
• {
• alert("Welcome - " + fullname);
• }
• <form name="DetailsForm">
• Enter full name <input type ="text"
id="fullname"/><br>
• <input type="button"
onClick="details(fullname.value)"
value="ClickMe"/>
Functions
• Separate piece of code which can be called and
executed whenever desired.
• Can be written anywhere in the web-page or in a
different page
• Look like this:
• <script>
• Function hello()
• {
• alert(“Hello!”)
• }
• </script>
Functions...
• Brackets beside the name allow a
parameter to be passed to the function
when running.
• Also allow a value to be passed back to
the main code once the function has run.
• Prompt box takes an input from user:
• X=prompt(“message”,””)
Function activity
• <head><script type=“text/vbscript”>
• Function topping()
• {
• Topp=prompt(“Enter a topping”,””)
• Alert(topp + “ “ + food)
• }
• </script></head>
Function activity...
• <body>
• <script type=“text/vbscript”>
• Food=“pizza”
• Topping(food)
• </script>
• </body>
Function activity
• Create the pizza script.
• Adapt it to allow the user to enter their
favourite food
• If the favourite food is pizza then call the
topping function
Properties
• Characteristics of objects in code eg:
• Type
• Name – can have more than one element
with same name
• id – must be unique
• Value
• Width
• height
Handling events
• Javascript is an event-driven language
• An event is an action which triggers a
reaction from the code.
• An event handler is a routine that picks up
an action that affects the object
• Eg onMouseOver, onClick
• Many Javascript events will be triggered in
this way.
• They work like this...
Other examples (event
handling)• Onfocus event
– <form>
– <input type =“text” onfocus= “ alert(‘An onFocus event’) “
– </form>
• Onmouseover event
– <img src=“image1.gif”
– OnMouseOver=alert(‘An onMouseOver event’)”
• Onload event
– <body onload=alert(“loaded”)>
• Text of the alert must not contain spaces. Can do more
by calling a function from the onload.
– <body onload=“functionname”()”>
Event driven example...
• <html>
• <head>
• <title>Using Javascript</title>
• <script type=“text/javascript”>
• </head>
• <body>
• </body>
• </html>
Event driven example...
• After <script type=“text/javascript”>
• add
• Function showalert()
• {
• Alert(“Hello world!”);
• }
• </script>
Event driven example...
• In the body add...
• <form method=“post” action =“”>//the method attribute is
post
• <p><button type=“button”
name =“callscript” onclick=“showalert();”>/* This is a button
tag with the name attribute callscript, it has an onclick
event with a value of showalertText for the button eg.*/
show the alert
</button></p>
</form>
Save the page, open and explore.
Event handling
• An event that triggers a piece of code
• Some examples and further explanation
are here:
• http://www.w3.org/TR/html4/interact/script
s.html#h-18.2.3
P3 Create a presentation:
• Explain what a scripting language is.
• Explain how a scripting language would
work in a web-page give examples of
object-oriented and event-driven.
• Explain the main features of a scripting
language.
Alternatively provide this information as a
web-page or as a report (about 500 words
Presentation should last about 5 minutes.
P3 Notes
This is a straightforward description. Be sure to describe
the terms:
• Object-driven
– methods
– properties
• Event-driven
– handling events
• security issues
• Constructs
– decision making
– loops
– Functions
– syntax
Give
examples!
M2
• Client vs server is not needed
• Compare examples of object-orientated and event-
driven
• Explain how Javascript improves functionality:– Drop-down menus
– Mouse-followers
– Image galleries
– Validation
– Browser detection
– Create cookies
– Read/write/modify HTML elements
• hiding or showing elements
• moving elements
• changing colors or fonts
D1
• Understanding client-side scripting
• Sheryl Canter, April 2004
• http://www.pcmag.com/article2/0,2817,155
4984,00.asp