SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
1
Client-side Scripting with
JavaScript
INFO 344 Winter 2007
Previously
Creating documents with HTML
Styling content with CSS
Dynamic documents with PHP
User input with web forms
Usability, design
Accessibility
Any questions?
The Project
You should have an idea by today
By Tuesday, Jan 30 you should
have
Description
Diagram
Wireframes
Writing assignment is due Tuesday
Feb 6
Examples/Ideas
Metafilter
http://www.metafilter.com/
http://www.jjg.net/ia/visvocab/files/m
etafilter_ia.pdf
This week
Expanding our web toolkit
JavaScript: Adding smartness to
the browser
Previously
2
Adding client-side scripting JavaScript
JavaScript is a client-side scripting
language
Executed by browser
Can’t interact with the server (without
help)
Can’t directly interact with PHP
Can’t interact with file system
What JavaScript can do
Perform simple computation
Math, string operations, etc.
Change page contents
Add and remove HTML elements
Change text and image contents
Control the browser
Navigate to pages
Open windows
Including JavaScript
Can be included in page
Use <script> tags within <head>
Can be placed in an external file
Create .js file with JS code in it
Use <script> tag within <head> to link
Embedding JS in a page
<html>
<head>
<title>JavaScript Test</title>
<script type="text/javascript">
var msg = "Hi everybody!";
alert(msg);
</script>
</head>
<body>
<!-- body goes here -->
</body>
</html>
Linking to a JS file
<html>
<head>
<title>JavaScript Test</title>
<script type="text/javascript"
src="library.js"/></script>
</head>
<body> <!-- body goes here --> </body>
</html>
in library.js:
var msg = "Hi everybody!";
alert(msg);
3
JavaScript language basics
Statements
Statements are terminated in a
semicolon
var hello = "Hi everybody";
var sum = 3 + 5;
Variables
Variable names don’t start with $
Declare variables similar to PHP
sum = 4 + 5;
name = “Jim";
Using var before a variable name
gives it a global scope
var age = 25;
Types
Number
Both integers and floats
String
Single or double quotes OK
Escape characters: n, t, "
Boolean
More on types
Type casting uses a function syntax
document.write("5" + 5); // 55
document.write(Number("5") + 5); //
10
Strings are concatenated using +,
not .
document.write(a + " plus " + b + " = "
+ (a+b));
Displaying output
The document.write() function
inserts its argument into the page
document.write ("Hello, " + name + "!");
The alert() function presents its
argument in a pop-up window
alert("Hello, " + name + "!");
4
Arrays
Similar to PHP, some syntax differences
var list = new Array(); // create new array
list[0] = "bananas"; // add to index 0
alert(list[0]); // 0th item: "bananas"
list.push("apples"); // use push to append
size = list.length; // size of array: 2
list.sort(); // this one is a method
list[2] = 5; // arrays can be of mixed type
// now ["apples", "bananas", 5]
More about arrays
Associative arrays
var zodiac = new Array();
zodiac["shaun"] = "Leo";
alert(zodiac["shaun"]); // "Leo"
Shorthand declaration
var groceries = new Array("bread", "milk", "cheese");
Loop through an array
for (item in groceries) {
document.write(item + "<br/>"); // writes
all items
}
Loops
Identical to PHP
for (var i = 0; i < 20; i++) {
document.write(I + "<br/>n");
}
while (info344=="awesome") {
comeToClass();
}
Conditionals
Uses else if, not elseif
if (total > 21) {
alert("you bust!);
}
else if (total < 22 && total >= 16) {
alert("Stand!");
}
else {
alert("Hit!");
}
Functions
Nearly identical to PHP
function power(base, exponent) {
var total = 1;
for (var i = 0; i < exponent; i++) {
total = total * base;
}
return total;
}
Objects
Can declare objects in JavaScript
Use function syntax
function Student(name, id) {
this.name = name;
this.id = id;
}
Use dot-notation to access them
var betty = new Student("Betty", 100);
alert (betty.id); // 100
5
The eval function
Can be used to execute arbitrary JS
code held in a string
Evaluates code and returns the result
var sum = eval("2 + 7");
document.write(sum); // 9
Beware security issues
Equivalent eval() function in PHP
Escaping text
Identical to PHP
“” (backslash)
alert(“To continue, please press the ”OK”
button.”);
’
”
n = new line
f = line feed
r = carriage return
& = ampersand
Comments
Identical to Java and PHP
// this is a one-line comment
/* this is
a multi-line
comment */
Using JavaScript
Adding JavaScript to pages
JavaScript may be used inline
Output text in document, like PHP
Most JavaScript is event-driven
Define functions
Attach functions to events (e.g. clicking
a button)
Functions run when the event occurs
Inline JavaScript
…
<body>
<p>Document last modified:
<script type="text/javascript">
document.write(document.lastM
odified);
</script>
</p>
</body>
6
Event-driven JavaScript
<html><head>
<script type="text/javascript">
function welcome() {
alert("hey there!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me"
onclick="welcome();"/>
</form>
</body></html>
Input type "button"
Button element
Looks like submit button
By default, does nothing
Attribute "value" determines button
text
Use onclick to add behavior
<input type="button" value="Click me"
onclick="welcome();"/>
onclick handler
The onclick handler fires whenever
an item is clicked
Applies to most items that can be
clicked on (links, buttons, images)
May reference a function defined in a
<script> tag
<a href="#" onclick="alert('Hey!');">
This is a JavaScript-powered link</a>
Other event handlers
onclick
onmouseover, onmouseout
onblur, onfocus
onload (for window object)
onsubmit (for forms)
… and many more!
See
http://www.quirksmode.org/js/events_compi
nfo.html
Referencing form elements
Referencing elements
Often we would like our scripts to
reference an element on the page
Get the contents of a text field
Change color of some text
Two methods for referencing page
elements
Form referencing
Document Object Model (DOM)
7
Referencing forms in JS
When creating forms and inputs, we give
each element a name
Refer to object using
document.formName.elementName
<body>
<form name="emailForm">
<input type="text" name="address"/>
</form>
</body>
document.emailForm.address
Accessing form values
Attribute value contains the value of most
form elements
document.emailForm.address.value = "a@b.com"; // set
alert(document.emailForm.address.value); // "a@b.com"
Use checked attribute for checkboxes
if (document.emailForm.cb1.checked) {
// cb1 is checked …
}
else {
// it's not …
}
The Document Object Model
DOM provides a set of methods for
accessing HTML elements (not just in forms)
Takes advantage of XHTML's tree
structure
document object represents root page element
Allows us to reference elements by ID or
tag name
And their parents, children and siblings
Can be used to modify page attributes
DOM methods
document.getElementById(id)
Retrieves the element with the specified id
Returns an element object (more on this later)
// gets the page element with id="email"
email = document.getElementById("email");
// display contents of element with id="email"
alert(email.value);
More methods we'll talk about later
The id attribute
Can be added to any XHTML element
Not just form elements
id must be unique on page
Form elements may have both name and
id
<body>
<form name="emailForm">
<input type="text" name="address"
id="address"/>
</form>
</body>
document.emailForm.address, or
document.getElementById("address")
Changing page content with the
DOM
We can also change the content of an HTML
element using its innerHTML property
<script type="text/javascript">
// when this function fires, add text to paragraph
function addResult() {
document.getElementById("change").innerHTML
="HI";
//c.innerHTML = "Success!";
}
</script>
<p id="change">New text will replace this.</p>
<input type="button" value="Click"
onclick="addResult();"/>
8
Validating forms with JS
Form validation
Can be performed on client-side or
server-side
Attach validation function to form's
onsubmit handler
If validation function returns true,
form passes data
If false, form does not submit
Validation example: form
<form name="emailForm"
action="submit.php" method="get"
onsubmit="return validate();">
Enter your email address:
<input type="text" name="address"/>
<input type="submit" value="Submit"/>
</form>
Validation example: script
<script type="text/javascript">
function validate() {
if (document.emailForm.address.value == "")
{
alert("Please enter your email
address!");
return false;
}
else {
return true;
}
}
</script>
Design considerations
Server-side vs. client-side
Server-side code (PHP)
Executes before browser loads page
Can interact with external sources (databases,
etc)
Requires page refresh
Client-side code (JavaScript)
Executes after page loads
Can't directly interact with other sources
More responsive, no page refresh needed
The two are often useful in combination
9
Compatibility issues
Can't expect JavaScript to work
everywhere
Different browsers support different features
Some users turn JavaScript off
Older browsers, non-graphical browsers,
mobile browsers, etc…
Solution: Provide redundant
functionality with PHP
PHP works on all browsers
Providing alternatives
Form validation can be performed both in PHP
and JavaScript
Use redundant validation
Perform JS validation as above
Validate in PHP script as well
<form name="emailForm" action="submit.php"
method="get" onsubmit="return validate();">
Alternatives
Links: Provide JS functionality in
JavaScript, comparable PHP version
as link
Non-JS browsers ignore onclick
JS browsers return false, don't follow
PHP link
<a href="phpFunction.php"
onclick="jsFunction(); return false;">
Link text</a>
Debugging JavaScript
JavaScript pages can be run locally
in browser
No great debugging tools for JS
Use Firefox's JavaScript Console to
debug your code
JavaScript Security
Cross Site Scripting (XSS)
JS from one domain cannot access
pages from another domain
No access to file systems
JS cannot read data from an external
file
Code injection
Unvalidated user input can inject JS
code into a response page
Where to get help
JavaScript Kit syntax references
http://www.javascriptkit.com/jsref/
http://www.javascriptkit.com/domref/
W3Schools JavaScript tutorial
http://www.w3schools.com/js/default.asp
QuirksMode has information regarding
which browsers support which
functions
http://www.quirksmode.org/
10
Questions?
Pop Quiz
What’s the JavaScript syntax
for declaring a global
variable?
1. global MyVar;
2. global $MyVar
3. var MyVar
4. declare MyVar
Pop Quiz
What output does the following code produce?
function MyFunc(limit) {
var step = 2;
for (var i = 0; i <= limit; i++) {
total = step * i;
document.write(total + "<br />");
}
}
MyFunc(100);
test
Pop Quiz
Which of the following things can
JavaScript NOT do?
1. Open new browser windows
2. Change content on the page
3. Read data from an external
file
4. Validate user input
Pop Quiz
True or False?
Javascript statements must end with
a semi-colon?
FALSE
Pop Quiz
DOM is an acronym for
1. Document Object Model
2. Distributed Object Method
3. Document Orientation
Model
4. Data Object Model
11
Next
Overview of extra credit assignment
JavaScript lab
Advanced JavaScript
(Time permitting)
Getting user input
confirm() allows you to display an OK/Cancel
dialog
Returns true or false
exit = confirm("Are you sure you want to leave?");
if (exit) { /* leave page */ }
prompt() allows you to create a pop-up dialog
that requests information
name = prompt("What is your name");
alert("Hello, " + name + "!");
Passing PHP variables to JS
Can pass from PHP to JS using echo
<script type="text/javascript">
var address = "http://google.com";
// pass variable "name" from PHP to JS
<?php
echo "var name = " . $name .
";n";
?>
</script>
Passing JS variables to PHP
Can set a hidden input using JavaScript
<script type="text/javascript">
var size = "giant";
// pass variable "size" to PHP
document.form1.size = size;
</script>
…
<form name="form1" action="submit.php">
<input name="size" type="hidden" value=""/>
</form>
Opening windows with JavaScript
The window.open() function can be
used to open additional browser
windows
Syntax:
var name = window.open(url,
windowName, params)
See
http://www.javascriptkit.com/javatutors/
window1.shtml
12
window.open() example
<script type="text/javascript">
function openWindow(url) {
// we can reference this window with variable 'win'
var win = window.open(url, 'win',
'width=600,height=500,status');
}
</script>
…
<a href="win.html" onclick="openWindow('win.html');
return false;">Open window</a>

Contenu connexe

Tendances

Html5, a gentle introduction
Html5, a gentle introduction Html5, a gentle introduction
Html5, a gentle introduction Diego Scataglini
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance TipsRavi Raj
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blogPierre Sudron
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the FinishYehuda Katz
 
Web Projects: From Theory To Practice
Web Projects: From Theory To PracticeWeb Projects: From Theory To Practice
Web Projects: From Theory To PracticeSergey Bolshchikov
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIOliver Häger
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery EssentialsMark Rackley
 
Unchain Your Web Development With Django
Unchain Your Web Development With DjangoUnchain Your Web Development With Django
Unchain Your Web Development With DjangoJoey Wilhelm
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important PartsSergey Bolshchikov
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebRobert Nyman
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
SproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFestSproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFesttomdale
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery PresentationRod Johnson
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseChristopher Singleton
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Eventsdmethvin
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with VaadinPeter Lehto
 

Tendances (20)

Html5, a gentle introduction
Html5, a gentle introduction Html5, a gentle introduction
Html5, a gentle introduction
 
Web Performance Tips
Web Performance TipsWeb Performance Tips
Web Performance Tips
 
Django workshop : let's make a blog
Django workshop : let's make a blogDjango workshop : let's make a blog
Django workshop : let's make a blog
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
Web Projects: From Theory To Practice
Web Projects: From Theory To PracticeWeb Projects: From Theory To Practice
Web Projects: From Theory To Practice
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
QCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UIQCon 2015 - Thinking in components: A new paradigm for Web UI
QCon 2015 - Thinking in components: A new paradigm for Web UI
 
SharePoint and jQuery Essentials
SharePoint and jQuery EssentialsSharePoint and jQuery Essentials
SharePoint and jQuery Essentials
 
Unchain Your Web Development With Django
Unchain Your Web Development With DjangoUnchain Your Web Development With Django
Unchain Your Web Development With Django
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 
HTML5 - The 2012 of the Web
HTML5 - The 2012 of the WebHTML5 - The 2012 of the Web
HTML5 - The 2012 of the Web
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
SproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFestSproutCore is Awesome - HTML5 Summer DevFest
SproutCore is Awesome - HTML5 Summer DevFest
 
Client Web
Client WebClient Web
Client Web
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
前端概述
前端概述前端概述
前端概述
 
ASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server DatabaseASP.Net, move data to and from a SQL Server Database
ASP.Net, move data to and from a SQL Server Database
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
jQuery
jQueryjQuery
jQuery
 
GWT integration with Vaadin
GWT integration with VaadinGWT integration with Vaadin
GWT integration with Vaadin
 

En vedette

Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arraysmussawir20
 
Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in phpChetan Patel
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersVineet Kumar Saini
 
Php tutorial
Php tutorialPhp tutorial
Php tutorialNiit
 

En vedette (6)

Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
 
Strings
StringsStrings
Strings
 
Useful functions for arrays in php
Useful functions for arrays in phpUseful functions for arrays in php
Useful functions for arrays in php
 
Top 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and AnswersTop 100 PHP Interview Questions and Answers
Top 100 PHP Interview Questions and Answers
 
Php tutorial
Php tutorialPhp tutorial
Php tutorial
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 

Similaire à lect4

計算機概論20161212
計算機概論20161212計算機概論20161212
計算機概論20161212志宇 許
 
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
 
Java script frame history
Java script frame historyJava script frame history
Java script frame historyH K
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It TodayDoris Chen
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script AdvanceJaya Kumari
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4DEVCON
 
Java script frame window
Java script frame windowJava script frame window
Java script frame windowH K
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAravindharamanan S
 
JavaServer Pages
JavaServer Pages JavaServer Pages
JavaServer Pages profbnk
 
Creating web api and consuming part 2
Creating web api and consuming part 2Creating web api and consuming part 2
Creating web api and consuming part 2Dipendra Shekhawat
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2borkweb
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and ImprovedTimothy Fisher
 

Similaire à lect4 (20)

計算機概論20161212
計算機概論20161212計算機概論20161212
計算機概論20161212
 
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
 
Java script frame history
Java script frame historyJava script frame history
Java script frame history
 
jQuery
jQueryjQuery
jQuery
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Java Script (Module 1).pptx
Java Script (Module 1).pptxJava Script (Module 1).pptx
Java Script (Module 1).pptx
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Tutorial asp.net
Tutorial  asp.netTutorial  asp.net
Tutorial asp.net
 
Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
Java script Advance
Java script   AdvanceJava script   Advance
Java script Advance
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
 
Java script frame window
Java script frame windowJava script frame window
Java script frame window
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
 
JavaServer Pages
JavaServer Pages JavaServer Pages
JavaServer Pages
 
Creating web api and consuming part 2
Creating web api and consuming part 2Creating web api and consuming part 2
Creating web api and consuming part 2
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
 
HTML5 New and Improved
HTML5   New and ImprovedHTML5   New and Improved
HTML5 New and Improved
 

Plus de tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

Plus de tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Dernier

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Dernier (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

lect4

  • 1. 1 Client-side Scripting with JavaScript INFO 344 Winter 2007 Previously Creating documents with HTML Styling content with CSS Dynamic documents with PHP User input with web forms Usability, design Accessibility Any questions? The Project You should have an idea by today By Tuesday, Jan 30 you should have Description Diagram Wireframes Writing assignment is due Tuesday Feb 6 Examples/Ideas Metafilter http://www.metafilter.com/ http://www.jjg.net/ia/visvocab/files/m etafilter_ia.pdf This week Expanding our web toolkit JavaScript: Adding smartness to the browser Previously
  • 2. 2 Adding client-side scripting JavaScript JavaScript is a client-side scripting language Executed by browser Can’t interact with the server (without help) Can’t directly interact with PHP Can’t interact with file system What JavaScript can do Perform simple computation Math, string operations, etc. Change page contents Add and remove HTML elements Change text and image contents Control the browser Navigate to pages Open windows Including JavaScript Can be included in page Use <script> tags within <head> Can be placed in an external file Create .js file with JS code in it Use <script> tag within <head> to link Embedding JS in a page <html> <head> <title>JavaScript Test</title> <script type="text/javascript"> var msg = "Hi everybody!"; alert(msg); </script> </head> <body> <!-- body goes here --> </body> </html> Linking to a JS file <html> <head> <title>JavaScript Test</title> <script type="text/javascript" src="library.js"/></script> </head> <body> <!-- body goes here --> </body> </html> in library.js: var msg = "Hi everybody!"; alert(msg);
  • 3. 3 JavaScript language basics Statements Statements are terminated in a semicolon var hello = "Hi everybody"; var sum = 3 + 5; Variables Variable names don’t start with $ Declare variables similar to PHP sum = 4 + 5; name = “Jim"; Using var before a variable name gives it a global scope var age = 25; Types Number Both integers and floats String Single or double quotes OK Escape characters: n, t, " Boolean More on types Type casting uses a function syntax document.write("5" + 5); // 55 document.write(Number("5") + 5); // 10 Strings are concatenated using +, not . document.write(a + " plus " + b + " = " + (a+b)); Displaying output The document.write() function inserts its argument into the page document.write ("Hello, " + name + "!"); The alert() function presents its argument in a pop-up window alert("Hello, " + name + "!");
  • 4. 4 Arrays Similar to PHP, some syntax differences var list = new Array(); // create new array list[0] = "bananas"; // add to index 0 alert(list[0]); // 0th item: "bananas" list.push("apples"); // use push to append size = list.length; // size of array: 2 list.sort(); // this one is a method list[2] = 5; // arrays can be of mixed type // now ["apples", "bananas", 5] More about arrays Associative arrays var zodiac = new Array(); zodiac["shaun"] = "Leo"; alert(zodiac["shaun"]); // "Leo" Shorthand declaration var groceries = new Array("bread", "milk", "cheese"); Loop through an array for (item in groceries) { document.write(item + "<br/>"); // writes all items } Loops Identical to PHP for (var i = 0; i < 20; i++) { document.write(I + "<br/>n"); } while (info344=="awesome") { comeToClass(); } Conditionals Uses else if, not elseif if (total > 21) { alert("you bust!); } else if (total < 22 && total >= 16) { alert("Stand!"); } else { alert("Hit!"); } Functions Nearly identical to PHP function power(base, exponent) { var total = 1; for (var i = 0; i < exponent; i++) { total = total * base; } return total; } Objects Can declare objects in JavaScript Use function syntax function Student(name, id) { this.name = name; this.id = id; } Use dot-notation to access them var betty = new Student("Betty", 100); alert (betty.id); // 100
  • 5. 5 The eval function Can be used to execute arbitrary JS code held in a string Evaluates code and returns the result var sum = eval("2 + 7"); document.write(sum); // 9 Beware security issues Equivalent eval() function in PHP Escaping text Identical to PHP “” (backslash) alert(“To continue, please press the ”OK” button.”); ’ ” n = new line f = line feed r = carriage return & = ampersand Comments Identical to Java and PHP // this is a one-line comment /* this is a multi-line comment */ Using JavaScript Adding JavaScript to pages JavaScript may be used inline Output text in document, like PHP Most JavaScript is event-driven Define functions Attach functions to events (e.g. clicking a button) Functions run when the event occurs Inline JavaScript … <body> <p>Document last modified: <script type="text/javascript"> document.write(document.lastM odified); </script> </p> </body>
  • 6. 6 Event-driven JavaScript <html><head> <script type="text/javascript"> function welcome() { alert("hey there!"); } </script> </head> <body> <form> <input type="button" value="Click me" onclick="welcome();"/> </form> </body></html> Input type "button" Button element Looks like submit button By default, does nothing Attribute "value" determines button text Use onclick to add behavior <input type="button" value="Click me" onclick="welcome();"/> onclick handler The onclick handler fires whenever an item is clicked Applies to most items that can be clicked on (links, buttons, images) May reference a function defined in a <script> tag <a href="#" onclick="alert('Hey!');"> This is a JavaScript-powered link</a> Other event handlers onclick onmouseover, onmouseout onblur, onfocus onload (for window object) onsubmit (for forms) … and many more! See http://www.quirksmode.org/js/events_compi nfo.html Referencing form elements Referencing elements Often we would like our scripts to reference an element on the page Get the contents of a text field Change color of some text Two methods for referencing page elements Form referencing Document Object Model (DOM)
  • 7. 7 Referencing forms in JS When creating forms and inputs, we give each element a name Refer to object using document.formName.elementName <body> <form name="emailForm"> <input type="text" name="address"/> </form> </body> document.emailForm.address Accessing form values Attribute value contains the value of most form elements document.emailForm.address.value = "a@b.com"; // set alert(document.emailForm.address.value); // "a@b.com" Use checked attribute for checkboxes if (document.emailForm.cb1.checked) { // cb1 is checked … } else { // it's not … } The Document Object Model DOM provides a set of methods for accessing HTML elements (not just in forms) Takes advantage of XHTML's tree structure document object represents root page element Allows us to reference elements by ID or tag name And their parents, children and siblings Can be used to modify page attributes DOM methods document.getElementById(id) Retrieves the element with the specified id Returns an element object (more on this later) // gets the page element with id="email" email = document.getElementById("email"); // display contents of element with id="email" alert(email.value); More methods we'll talk about later The id attribute Can be added to any XHTML element Not just form elements id must be unique on page Form elements may have both name and id <body> <form name="emailForm"> <input type="text" name="address" id="address"/> </form> </body> document.emailForm.address, or document.getElementById("address") Changing page content with the DOM We can also change the content of an HTML element using its innerHTML property <script type="text/javascript"> // when this function fires, add text to paragraph function addResult() { document.getElementById("change").innerHTML ="HI"; //c.innerHTML = "Success!"; } </script> <p id="change">New text will replace this.</p> <input type="button" value="Click" onclick="addResult();"/>
  • 8. 8 Validating forms with JS Form validation Can be performed on client-side or server-side Attach validation function to form's onsubmit handler If validation function returns true, form passes data If false, form does not submit Validation example: form <form name="emailForm" action="submit.php" method="get" onsubmit="return validate();"> Enter your email address: <input type="text" name="address"/> <input type="submit" value="Submit"/> </form> Validation example: script <script type="text/javascript"> function validate() { if (document.emailForm.address.value == "") { alert("Please enter your email address!"); return false; } else { return true; } } </script> Design considerations Server-side vs. client-side Server-side code (PHP) Executes before browser loads page Can interact with external sources (databases, etc) Requires page refresh Client-side code (JavaScript) Executes after page loads Can't directly interact with other sources More responsive, no page refresh needed The two are often useful in combination
  • 9. 9 Compatibility issues Can't expect JavaScript to work everywhere Different browsers support different features Some users turn JavaScript off Older browsers, non-graphical browsers, mobile browsers, etc… Solution: Provide redundant functionality with PHP PHP works on all browsers Providing alternatives Form validation can be performed both in PHP and JavaScript Use redundant validation Perform JS validation as above Validate in PHP script as well <form name="emailForm" action="submit.php" method="get" onsubmit="return validate();"> Alternatives Links: Provide JS functionality in JavaScript, comparable PHP version as link Non-JS browsers ignore onclick JS browsers return false, don't follow PHP link <a href="phpFunction.php" onclick="jsFunction(); return false;"> Link text</a> Debugging JavaScript JavaScript pages can be run locally in browser No great debugging tools for JS Use Firefox's JavaScript Console to debug your code JavaScript Security Cross Site Scripting (XSS) JS from one domain cannot access pages from another domain No access to file systems JS cannot read data from an external file Code injection Unvalidated user input can inject JS code into a response page Where to get help JavaScript Kit syntax references http://www.javascriptkit.com/jsref/ http://www.javascriptkit.com/domref/ W3Schools JavaScript tutorial http://www.w3schools.com/js/default.asp QuirksMode has information regarding which browsers support which functions http://www.quirksmode.org/
  • 10. 10 Questions? Pop Quiz What’s the JavaScript syntax for declaring a global variable? 1. global MyVar; 2. global $MyVar 3. var MyVar 4. declare MyVar Pop Quiz What output does the following code produce? function MyFunc(limit) { var step = 2; for (var i = 0; i <= limit; i++) { total = step * i; document.write(total + "<br />"); } } MyFunc(100); test Pop Quiz Which of the following things can JavaScript NOT do? 1. Open new browser windows 2. Change content on the page 3. Read data from an external file 4. Validate user input Pop Quiz True or False? Javascript statements must end with a semi-colon? FALSE Pop Quiz DOM is an acronym for 1. Document Object Model 2. Distributed Object Method 3. Document Orientation Model 4. Data Object Model
  • 11. 11 Next Overview of extra credit assignment JavaScript lab Advanced JavaScript (Time permitting) Getting user input confirm() allows you to display an OK/Cancel dialog Returns true or false exit = confirm("Are you sure you want to leave?"); if (exit) { /* leave page */ } prompt() allows you to create a pop-up dialog that requests information name = prompt("What is your name"); alert("Hello, " + name + "!"); Passing PHP variables to JS Can pass from PHP to JS using echo <script type="text/javascript"> var address = "http://google.com"; // pass variable "name" from PHP to JS <?php echo "var name = " . $name . ";n"; ?> </script> Passing JS variables to PHP Can set a hidden input using JavaScript <script type="text/javascript"> var size = "giant"; // pass variable "size" to PHP document.form1.size = size; </script> … <form name="form1" action="submit.php"> <input name="size" type="hidden" value=""/> </form> Opening windows with JavaScript The window.open() function can be used to open additional browser windows Syntax: var name = window.open(url, windowName, params) See http://www.javascriptkit.com/javatutors/ window1.shtml
  • 12. 12 window.open() example <script type="text/javascript"> function openWindow(url) { // we can reference this window with variable 'win' var win = window.open(url, 'win', 'width=600,height=500,status'); } </script> … <a href="win.html" onclick="openWindow('win.html'); return false;">Open window</a>