Resources:
JavaScript Guide - MDC Doc Centerdeveloper.mozilla.org/en/JavaScript/Guide
Mozilla JavaScript Scripting Resources www.mozilla.org/js/scripting
Introduction
• Introduction to JavaScript– NOT Java
• JavaScript was developed by Netscape– Java was developed by Sun
• Designed to ‘plug a gap’ in the techniques– available for creating web-pages
• Client-side dynamic content• Interpreted language
JavaScript
JavaScript vs JAVA
Historically…• Complementary– JavaScript
• Cannot draw, multi-thread, network or do I/O– Java
• Cannot interact with Browser or control content
JavaScript
JavaScript vs JAVA
• JavaScript is becoming what Java was – originally intended to be– Java Applets were meant to be lightweight
• downloadable programs run within the browser for cross-platform compatibility
• JAVA was slow, inefficient• JAVA had many implementations• JavaScript is actually lightweight
– accomplish most of what Applets do with a – fraction of the resources
JavaScript
JavaScript Versions
JavaScript
JavaScript 1.5 was introduced back in 1999, so no worries.
JavaScript is derived from a standard called ECMAScript.
In most browsers JavaScript = JavaScript.However, in some browser it is not true… e.g. Microsoft Internet Explorer -> JScript.
JavaScript today...• What is it used for today?
– Handling User Interaction– Doing calculations– Checking for accuracy and appropriateness of data in forms
• Doing calculations/manipulations of forms input data• Search a small databased embedded in the downloaded page• Save data as cookie so it is there upon visiting the page• Generating Dynamic HTML documents• Examples
– Bookmarklets– Google Maps– Google Suggest
JavaScript
Embedding scripts in HTML
<script type="text/javascript">
// Write a headingdocument.write("<h1>This is a heading</h1>");
// Write two paragraphs:document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>");
</script>
<script type="text/javascript" src="script.js"></script>
JavaScript Language Syntax
Variables and Literals
• Declaration– Explicit: var i = 12; // no ‘var’ in declaration– Implicit: i = 12;
• Variable Scope– Global
• Declared outside functions• Any variable implicitly defined
– Local• Explicit declarations inside functions
JavaScript Language Syntax
Variables and Literals
Dynamic Typing - Variables can hold any valid type: Number … var myInt = 7;Boolean … var myBool = true;Function … [Discussed Later] Object … [Discussed Later]Array … var myArr = new Array();
String … var myString = “abc”;Can hold values of different types
JavaScript Language Syntax
Arithmetic OperatorsOperator Description Example x y
+ Addition x=y+2 7 5
- Subtraction x=y-2 3 5
* Multiplication x=y*2 10 5
/ Division x=y/2 2.5 5
% Modulus (division remainder)
x=y%2 1 5
++ Increment x=++yx=y++
65
66
-- Decrement x=--yx=y--
45
44
JavaScript Language Syntax
Assignment OperatorsOperator Example Same As Result
= x = y x = 5
+= x += y x=x+y x=15
-= x -= y x=x-y x=5
*= x *= y x=x*y x=50
/= x /= y x=x/y x=2
%= x %= y x=x%y x=0
JavaScript Language Syntax
Control Flow• ‘if’ statement
if ( boolean statement ) {…} else {…}
• ‘switch’ statementswitch ( myVar ) {case 1: // if myVar is equal to 1 this is executedbreak;case default:// if none of the cases above are satisfied OR if no ‘break’ statement are used in the cases above, this will be executed
}
JavaScript Language Syntax
Control Flow
Check in the documentation:
• while, and do-while loops, for loops
• break and continue keywords
JavaScript
Functions
Call a function the same way You would in CmyFunc(arg1, arg2, …);
Declare a function using the ‘function’keywordNo return type, nor typing of arguments
function add(numOne, numTwo) {return numOne + numTwo;}
JavaScript
Output
The DOM document objects allows printing directly into the browser page • window object is implied
Writing in text or HTML with script– No line-breakdocument.write(“I am <B>BOLD</B>”);– With line-breakdocument.writeln(“I am <U>underlined</U>”);
JavaScript
A little more advanced…<script type="text/javascript">
var txt="";function message(){try { adddlert("Welcome guest!"); }catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } }}
</script>
JavaScript
Objects
• Not a full blown OO language, but object oriented
• You can define your own objects • You can make your own variable types.
Looking again at the previous slide…
JavaScript
Declaring Objects
function Lecture(myTime,myPlace, mySubject) {this.time = myTime;this.place = myPlace;this.subject = mySubject;
}var lect = new Lecture(„08:00”,“Here”, „JS”);
JavaScript
Working with Objects
• Accessing object’s properties
– document.writeln(‘Subject: ‘ + lect.subject);
• Objects and Associative Arrays are in fact two interfaces to the same data structure so…:
– document.writeln(‘Subject: ‘ + lect[“subject”]);
JavaScript
Inheritance in JavaScript
• No built-in inheritance
• Runtime Inheritance: Clone objects and add extra properties
JavaScript
Global Properties and Functions
decodeURI() Decodes a URI
encodeURI() Encodes a URI
escape() Encodes a string
eval() Evaluates a string and executes it as if it was script code
isFinite() Determines whether a value is a finite, legal number
isNaN() Determines whether a value is an illegal number
Number() Converts an object's value to a number
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer
String() Converts an object's value to a string
unescape() Decodes an encoded string
JavaScript
Built-in Objects (some)• Number, Boolean, String
– Primitive types are automatically converted to Objects when assigned to variables
var str = “abc”; //var is a String object!• String has some helpful properties/functions:
• length• toUpperCase• substring• link
– Date• No properties, but contains a bunch of methods for getting, setting and manipulating dates.
– Math• Calculate PI, find the SIN or COS of an angle, etc.
JavaScript
DOM and JS
• Browser – Built-in Objects– window.location– href represents a complete URL. – hostname represents the concatenation host:port. – window.location.href=“http://www.google.com”;
• window.history– length reflects the number of entries in the history list– history.go(-1)– history.back()
JavaScript
DOM and JS
• Window – alert("message")– window.close()– confirm("message") – focus() – open("URLname","Windowname",["options"])– height, weight, alwaysRaised, location, menubar
open(“http://google.com”, “Google”, “toolbar=no,alwaysRaised=yes”);
JavaScript
jQuery
• Very easy and powerful programming• Attempts to be cross-browser• Easier to support for multiple platforms• Implements document.ready() handlers• Full DOM support• Event propagation manipulation• Nice UI
JavaScript
Basic Usage Examples
• Adding a class– $("a").addClass("test");Note: HTML allows multiple classes to be added to an element.( <span class="class1 class2 class3"> )
• Removing a class– $("a").removeClass("test");
• Hide and show– $(this).hide();– $(this).show("slow");
• Selectors: # > .
JavaScript
jQuery selectors
:animated:enabled:even:first-child:has():hidden:button, :input, :image, etc…and more….
JavaScript
AJAX handlers<div class="trigger">Trigger</div> <div class="result"></div> <div class="log"></div>
$('.log').ajaxComplete(function() { $(this).text('Triggered ajaxComplete handler.');
});
$('.trigger').click(function() { $('.result').load('ajax/test.html');
});
JavaScript
Callback and Functions
• Posibility to define functions inline, e.g.
$(„a”).click(function() { $(this).css(‘border’,’1px solid black’);});
JavaScript
Callback and Functions
• A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
$.get('myhtmlpage.html', myCallBack);
JavaScript
Callback and Functions
• What is we want to pass arguments to a callback function?
WRONG:$.get('myhtmlpage.html', myCallBack(param1, param2));
This will not work because it calls the function and then passes the return value as the second parameter to $.get()
JavaScript
Callback and Functions
• What is we want to pass arguments to a callback function?
$.get('myhtmlpage.html', function(){ myCallBack(param1, param2);
});
JavaScript
jQuery Form Validation
• Simplest method is to use jQ plugin ( e.g. jquery.validate.js)
• Include jquery.js and jquery.validate.js in the head
• Run validate(); on the form object
JavaScript
jQuery Form Validation<form id="commentForm”> <p>
<label for="cname">Name</label> <em>*</em><input id="cname" name="name" size="25" class="required" minlength="2" />
</p>
<script> $(document).ready( function(){ $("#commentForm").validate(); });
</script>
Adding more rules:
$("#myinput").rules("add", { minlength: 2 });
JavaScript
jQuery Form Validation
$("#myinput").rules("add", { required: true, minlength: 2, messages: {
required: "Required input", minlength: jQuery.format("At least {0} characters are necessary")
} });
JavaScript
jQuery Form Validation
$("#myform").validate({ rules: { emailField: {
required: true, email: true
} }
});
JavaScript
Top Related