480 likes | 609 Views
JavaScript JQuery. JavaScript. Resources. Resources:. JavaScript Guide - MDC Doc Center developer. mozilla .org /en/ JavaScript /Guide Mozilla JavaScript Scripting Resources www.mozilla.org/ js / scripting. Introduction. Introduction to JavaScript NOT Java
E N D
JavaScriptJQuery JavaScript Resources
Resources: JavaScript Guide - MDC Doc Center developer.mozilla.org/en/JavaScript/Guide MozillaJavaScriptScripting 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 • Interpretedlanguage JavaScript
JavaScriptvs JAVA Historically… • Complementary – JavaScript • Cannot draw, multi-thread, network or do I/O • Java • Cannot interact with Browser or control content JavaScript
JavaScriptvs JAVA • JavaScript is becoming what Java was • originally intended to be • Java Applets weremeant to be lightweight • downloadable programs run within the browser for cross-platform compatibility • JAVAwas slow, inefficient • JAVA had many implementations • JavaScript is actually lightweight • accomplish most of what Applets do with a • fraction of the resources JavaScript
JavaScriptVersions JavaScript 1.5 was introduced back in 1999, so no worries. JavaScriptisderivedfrom a standard calledECMAScript. In most browsersJavaScript = JavaScript. However, insomebrowseritis not true… e.g. Microsoft Internet Explorer -> JScript. JavaScript
JavaScripttoday... • What is it used for today? • Handling User Interaction • Doing calculations • Checking for accuracy and appropriateness of data informs • 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
Want more… ? • GrooveShark.com • GoogleCalendar • Aviary.com • www.alexbuga.com • … JavaScript
Embedding scripts in HTML <scripttype="text/javascript"> // Write a headingdocument.write("<h1>This is a heading</h1>"); // Writetwoparagraphs:document.write("<p>Thisis a paragraph.</p>");document.write("<p>Thisisanotherparagraph.</p>"); </script> <scripttype="text/javascript" src="script.js"></script> JavaScript LanguageSyntax
Variables and Literals • Declaration • Explicit: var i = 12; // no ‘var’ indeclaration • Implicit: i = 12; • VariableScope • Global • Declaredoutsidefunctions • Any variableimplicitlydefined • Local • Explicitdeclarationsinsidefunctions JavaScript LanguageSyntax
Variables and Literals Dynamic Typing - Variables can hold any valid type: Number … varmyInt = 7; Boolean … varmyBool = true; Function … [Discussed Later] Object … [Discussed Later] Array … varmyArr = new Array(); String … varmyString = “abc”; Can hold values of different types JavaScript LanguageSyntax
ArithmeticOperators JavaScript LanguageSyntax
AssignmentOperators JavaScript LanguageSyntax
ControlFlow • ‘if’ statement if ( boolean statement ) { … } else { … } • ‘switch’ statement switch ( myVar ) { case 1: // if myVar is equal to 1 this is executed break; 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 LanguageSyntax
ControlFlow Checkinthedocumentation: • while, and do-while loops, for loops • break and continue keywords JavaScript
Functions Call a function the same way You would in C myFunc(arg1, arg2, …); Declare a function using the ‘function’keyword No 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-break document.write(“I am <B>BOLD</B>”); – With line-break document.writeln(“I am <U>underlined</U>”); JavaScript
A littlemoreadvanced… <scripttype="text/javascript">vartxt="";functionmessage(){try {adddlert("Welcomeguest!"); }catch(err) {txt="There was an error on thispage.\n\n";txt+="Click OK to continueviewingthispage,\n";txt+="orCancel to return to thehomepage.\n\n";if(!confirm(txt)) {document.location.href="http://www.w3schools.com/"; } }} </script> JavaScript
Objects • Not a fullblown OO language, but objectoriented • Youcandefine your own objects • Youcanmake your own variable types. Lookingagainatthepreviousslide… JavaScript
DeclaringObjects functionLecture(myTime,myPlace, mySubject) { this.time = myTime; this.place = myPlace; this.subject = mySubject; } varlect = newLecture(„08:00”,“Here”, „JS”); JavaScript
WorkingwithObjects • 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
InheritanceinJavaScript • No built-in inheritance • Runtime Inheritance: Clone objects and add extra properties JavaScript
Global Properties and Functions JavaScript
Built-inObjects (some) • Number, Boolean, String • Primitive types are automatically converted to Objects when assigned to variables varstr = “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
HTML Objects Hierarchy JavaScript
jQuery lightweightJavascriptframework JavaScript
jQ, HTML, DOM JavaScript
jQuery • Veryeasy and powerfulprogramming • Attempts to be cross-browser • Easier to support for multipleplatforms • Implementsdocument.ready() handlers • Full DOM support • Eventpropagationmanipulation • Nice UI JavaScript
jQ, HTML, DOM (FireBug) JavaScript
Basic UsageExamples • 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
jQueryselectors :animated :enabled :even :first-child :has() :hidden :button, :input, :image, etc… and more…. JavaScript
jQuerytraversing .add() .children() .each() .first() .is() .next() … 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
Eventpropagation (bubbling) To stop bubbling one canuseevent.stopPropagation(); JavaScript
Callback and Functions • Posibility to definefunctionsinline, 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 • Whatis we want to pass arguments to a callbackfunction? WRONG: $.get('myhtmlpage.html', myCallBack(param1, param2)); This will not work because it callsthefunctionand then passes the returnvalue as the second parameter to $.get() JavaScript
Callback and Functions • Whatis we want to pass arguments to a callbackfunction? $.get('myhtmlpage.html', function(){ myCallBack(param1, param2); }); JavaScript
$.get('myhtmlpage.html', myCallBack); jQuery UI JavaScript
jQuery Form Validation • Simplestmethodis to usejQplugin( e.g. jquery.validate.js) • Includejquery.js and jquery.validate.jsinthehead • 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> Addingmorerules: $("#myinput").rules("add", { minlength: 2 }); JavaScript
jQuery Form Validation $("#myinput").rules("add", { required: true, minlength: 2, messages: { required: "Required input", minlength: jQuery.format("Atleast {0} characters are necessary") } }); JavaScript
jQuery Form Validation $("#myform").validate({ rules: { emailField: { required: true, email: true } } }); JavaScript
ThankYou Questions? JavaScript