chapter 2 (is245)

Upload: ashhab-mahdi

Post on 04-Nov-2015

219 views

Category:

Documents


0 download

DESCRIPTION

Semo is 245

TRANSCRIPT

  • Modern JavaScriptDevelop And DesignInstructors NotesChapter 2- JavaScript in ActionModern JavaScript Design And DevelopCopyright 2012 by Larry Ullman

  • ObjectivesExplain what a DOCTYPE is and why it matters to Web pagesIdentify the two browser operating modesWrite the HTML5 DOCTYPECreate an HTML5 templateUse the new HTML5 form elements and attributes

  • More ObjectivesEmbed JavaScript in HTMLUnderstand how to properly write file pathsDefine and demonstrate key JavaScript development approachesLearn the basics of event handlingRetrieve a reference to a page element

  • Even More ObjectivesRecognize when the browser window is ready for dynamic behaviorDefine a simple user function.Perform basic validation of an HTML form

  • Document Type DeclarationShould be the first line of an HTML pageTells the browser what kind of HTML to expect, and therefore what kind of features to supportImpacts how the page looks and behavesProvides instruction to validators

  • Older DOCTYPEsHTML (2.0, 3.2, 4.01)XHTML (1.0, 1.1)Strict, Transitional, Frameset

  • Browser ModesBrowser modes are dictated by the DOCTYPETwo modes: Standards and QuirksInvalid DOCTYPEs and improper HTML can trigger Quirks mode

  • HTML5 DOCTYPE

    Short, easy to typeSupported by all major browsersAutomatically triggers Standards modeAllows you to begin using HTML5 features

  • HTML5The next logical HTML standardNot yet standardizedLots of new useful features, especially in formsMany features are usable today

  • HTML5 Template

    HTML5 Template

  • New HTML5 Input Typesemailnumberrangesearchtelurl

  • New HTML5 Form Attributesautofocusplaceholderrequiredmaxlength on textareasnovalidate (on entire form)

  • Adding JavaScript to HTML

    // Actual JavaScript code goes here.

  • Understanding PathsAbsoluteStart at a fixed location, such as the Web root directoryNormally begin with http:// or just /.The same absolute path is correct regardless of where the including file is.RelativeStart at the current location (i.e., the current files location).Begin with a file name, a folder name, or a period.A relative path is only correct for files with the same relative positions.

  • Paths ExampleIncluding script.js from page.html/js/script.jshttp://www.example.com/js/script.jsjs/script.js./js/script.js

  • Development ApproachesGraceful degradationProgressive enhancementUnobtrusive JavaScript

  • Graceful Degradation

    HTML5 Template

    You must have JavaScript enabled!

  • Progressive Enhancement

  • Object Detection

    if (/* some object is defined */) { // Use that object!}

  • Unobtrusive JavaScriptEasier to read and maintainCan be progressively enhancedDoes not require JavaScript to be enabled

  • Obtrusive JavaScriptA Link

  • A Basic ExampleStart with the HTMLEstablish baseline functionalityAdd a JavaScript layer, unobtrusivelyAdd enhanced functionality, when supported

  • An HTML Form

    Login Email Address Password

  • Baseline FunctionalityBy default, the form gets submitted to a server-side script.That functionality works on any device that can load an HTML form.

  • The JavaScript LayerHijack the form submission.Validate the form data.If valid, allow the submission to go through to the server.If invalid, display errors.

  • Handling EventsEvent handler = call this function when this event occurs on this element.In JavaScript code: element.onevent = functionwindow.onload = init;loginForm.onsubmit = validateForm;

  • Referencing Elementsvar email = document.getElementById('email');var password = document.getElementById('password');var loginForm = document.getElementById('loginForm');

  • Defining a Functionfunction functionName() { // Function code.}

    function init() { var loginForm = document.getElementById('loginForm'); loginForm.onsubmit = validateForm;

    } // End of init() function.

  • Strict Modefunction init() { use strict; var loginForm = document.getElementById('loginForm'); loginForm.onsubmit = validateForm;

    } // End of init() function.

  • Simple Validationif ( (email.value.length > 0) && (password.value.length > 0) ) { return true;} else { alert('Please complete the form!'); return false;}

    *****Aka DOCTYPENot only first line, but no space before itXHTML is HTML with XML syntaxStrict allows for the smallest set of elementsTransitional is Strict plus deprecated elements and moreFrameset is Transitional plus support for frames (boo)XHTML is now dead*Quirks mode renders the page in an old, safe way, which can have terrible resultsGreat JavaScript resource: quirksmode.org*The usable features are those that either degrade gracefully or can be made supported by more browsers by using secondary scripts.*HEAD element is not required in HTML5Title is requiredIndicate the encoding early in the document; must match actual encoding; utf-8 is common.Many other elements have been simplified: meta charset, stylesheet, and scriptThe HTML5 shiv creates support for new HTML5 tags on IE 8 and earlier.*Number is a spinbox.Range is a slider.Safe to use because browsers that dont support them will create plain text inputs.Support varies by browser*Autofocus gets focus when page is loaded.Placeholder is for temporary text.Required triggers validation.You will sometimes need to add novalidate to the opening form tag to test JavaScript on HTML5 supportive browsers.*No longer uses a type attribute in HTML5Code goes between the opening and closing tags.You can, and often will, use multiple instances of script within a single HTML page.You can write code within a script tag OR include an external JavaScript file, but not both.JavaScript files use the .js extension by default.The path to the external JavaScript resource must be correct.Script tags can go anywhere within the HTML; there are different benefits to different locations.*There are two ways of referring to site resources: absolutely or relatively*First two are absolute.Second two are relative.All are accurate.*1-3% of all clients are not capable of executing any JavaScript.Graceful degradation: A development approach wherein you define the desired functionality and then provide alternative content to those with JavaScript disabled.Progressive enhancement: A development approach wherein you define baseline functionality available to all clients and then enhance that functionality for clients that can support the enhancements. Progressive enhancement also involves CSS.*Uses noscript tagsNot terrible and absolutely necessary in some situations, but best to be avoided.*Opposite approach compared to graceful degradation. Establish base functionality for all browsers and then enhance functionality for browsers that can support it.*Progressive enhancement uses object detection: The process of testing support for features by specifically looking for the definition of key objects. SimpleWorks on all browsers and devices.The trick is in how you confirm an object exists, which youll learn about in time.

    *Obtrusive, or embedded, JavaScript will work, but is to be avoided. Its too hard to read and maintain, and cannot be progressively enhanced. Also implicitly assumes JavaScript is enabled.*Note that this is clean, sematic HTML, without any inline JavaScript.*Create unique ID values for elements to be referenced by the JavaScript.Include the external JavaScript file (login.js).*To use JavaScript, you must understand event handling. Here Ill introduce the basics.Every (or almost every) element in a Web browser, including the browser itself, can have eventsIn JavaScript in the Web browser, events are triggered by user actions and external actions, such as Ajax requests.User-defined functions handle the events.Two events needed for this simple example are the loading of the browser window and the submission of the HTML form.*In order to attach event handlers to page elements, youll need a reference to the elements involved. There are many ways of doing so. Document.getELementById() is universal and reliable.It takes an HTML id value as its argument and returns the single element that has that id.Note that HTML elements must have unique id values.*Keyword function, followed by the function name and parentheses. The functions contentthe code to be executed when the function is calledgoes within curly brackets.*Added in ECMAScript 5Potentially problematic code will cause errors (instead of be ignored)Improves security and performanceProvides warnings about code that will be deprecated

    *One simple way to validate form elements is to check for a positive length. Youll learn many other validation approaches in time.Similarly, alert() can be used as a simple error reporting tool, although its not ideal in many ways.Return false to prevent the forms actual submission.Returning true allows the submission to go through.*