SlideShare a Scribd company logo
1 of 91
Download to read offline
TRAINING JAVASCRIPT & jQUERY

    Editor: Nguyễn Đức Minh Khôi
Email: nguyenducminhkhoi@gmail.com
   HCMC University of Technology
             @Jan, 2012
Content
       Introduction to JavaScript

          JavaScript – the basic

           Getting Started with JQuery

          JQuery in Action

       Ajax, tips, tricks

2                                        1/6/2012
Part1: Introduction to JavaScript

      What is JavaScript and JQuery?


      The Web World


      Software for JavaScript programming



3                                           1/6/2012
What is JavaScript?
     JavaScript is a programming language that lets you
      supercharge your HTML with animation, interactivity,
      and dynamic visual effects.




4                                                     1/6/2012
What is jQuery?
     jQuery is a JavaScript library intended to make
      JavaScript programming easier and more fun.
     solves the two biggest headaches with JavaScript—
      complexity and the finicky nature of different web
      browsers.
     you can add advanced features to your website with
      thousands of easy-to-use jQuery plug-ins.




5                                                       1/6/2012
The web world
     HTML provides the structural layer, organizing content
      like pictures and words in a meaningful way
     CSS (Cascading Style Sheets) provides the
      presentational layer, making the content in the HTML
      look good
     JavaScript adds a behavioral layer, bringing a web page
      to life so it interacts with web visitors and reduce
      “stress” for Server.
     Other Server Scripting: PHP, ASP, JSP, Ruby, Python…
      do the main part of your project!

6                                                      1/6/2012
Software for JS Programming
     Notepad++ (Windows, http://notepad-plus-plus.org) is a
        coder’s friend.
       Netbeans (Windows, Linux, Mac; www.eclipse.org) is a
        free, popular choice amongst Java Developers, but
        includes tools for working with HTML, CSS, and JavaScript.
       Eclipse and Aptana Studio plugin (Windows, Linux, Mac;
        www.aptana.org) is a powerful, free coding environment
        with tools for working with HTML, CSS, JavaScript, PHP, and
        Ruby on Rails.
       Dreamweaver (Mac and Windows,
        www.adobe.com/products/dreamweaver.html) is a visual
        web page editor.
       Expression Web Designer (Windows,
        www.microsoft.com/expression/products/StudioWebPro_
        Overview.aspx) is Microsoft’s entry in the web design field.
7                                                             1/6/2012
Software for JS Programming (cont’)
     Google Chrome browser and Developer tools (Ctr +
        Shift + J)
       Firefox and firebug plugin (http://getfirebug.com/)
       Internet Explorer 9 – console (F12)
       Safari and Error console (Ctrl + Alt + C)
       Wamp Server (for Ajax practice) for windows
        www.wampserver.com/en/
       Lamp Server for Linux (Debian, Ubuntu)
        http://www.sph.umich.edu/csg/abecasis/LAMP/downl
        oad/
       Mamp Server for Mac: www.mamp.info/en

8                                                     1/6/2012
TRAINING JAVASCRIPT & jQUERY

    Editor: Nguyễn Đức Minh Khôi
Email: nguyenducminhkhoi@gmail.com
   HCMC University of Technology
             @Jan, 2012
Content
        Introduction to JavaScript

           JavaScript – the basic

            Getting Started with JQuery

           JQuery in Action

        Ajax, tips, tricks

10                                        1/6/2012
Part2: JavaScript – the Basics

     Introduction to JavaScript


     How to work with JavaScript



11                                    1/6/2012
Introduction to JavaScript
      How to add JS to a page:




      Notes: if you use HTML earlier than HTML5 should:



12                                                        1/6/2012
Introduction to JavaScript (cont.)
      URL type:
        Absolute path:
          http://www.cosmofarmer.com/scripts/site.js
          Use when you point to a file that’s not on the same server as the
           your web page.
        Root relative:
          /scripts/site.js
          Use for JavaScript files stored on your own site.
        Document relative:
          ../scripts/site.js - ../ means climb up out of the folder
          Use when you’re designing on your own computer without the
           aid of a web server.



13                                                                    1/6/2012
Introduction to JavaScript (cont.)
      JS is a client-side language which means that it works
         inside a web browser.
        JS is also a scripting language like PHP, Ruby, Python
         ColdFusion as well.
        JS is a multi-paradigm language, supporting object-
         oriented, imperative, and functional programming styles.
        JavaScript was formalized in the ECMAScript language
         standard.
        JavaScript uses syntax influenced by that of C. And very
         different sematic with Java.
        See more at http://www.w3schools.com/js/default.asp

14                                                              1/6/2012
Introduction to JavaScript (cont.)
      Statement
        Basic programming unit
        E.g.: alert('Hello World!');
      Popup Box:
        alert(‚Be alert‛) // alert something with user
        prompt(‚enter sth‛)//ask user to input something
        confirm("Press a button!");
      Built in function
        document.write() //add content to a page
        isNaN(variable) //check if variable is a number
        Number(variable) // convert to number or NaN
        String(variable) // convert to string
      Data Type
        Number: 5, 5.125, NaN (just– Double)
        String: ‘Hello’, ‚Hello‛, ‚Hello ’World’ !‛, ‚’a‛,
         ‚Hello‛World‛!‛
        Boolean: true, false
        Object
15      null, undefined                                   1/6/2012
Introduction to JavaScript (cont.)
      Variable
          Declare: var + varName;
          Name: abc ≠ Abc, $abc, _abc, a123, 1bcd, alert
          Assign: varName = value;
          Show values: alert(varName);
      Operation:
        Boolean op: ==, != , ===, !==, >, < , >=, <=, &&, ||, !
        Number op: 3 + 4, 3 / 4, 3 * 4, 3 – 4
        String op: ‘abc’ + ‘def’;
        Mix: ‘12’ + 4 = ‘124’; +’123’ + 4 = 127;
         Number(‘123’) + 4 = 127; ‘12’ * 4 = 48;
        Complex op: ++, --, *=, /=, +=, -=
        Ternary op: (condition) ? A : B



16                                                                 1/6/2012
Introduction to JavaScript (cont.)
      Comment:
        //this is a comment inline
        /*
             something to comment in many lines
                                     */
      Array (List in real)
        Declare:    var arr = [1, 2, 3]; or
                     var arr = new Array(1, 2, 3);
        Access: arr[0];
        Notes:
           Empty array: var arr = [];
           Mix types: var arr = [1, 2, ‘abc’, true, [3, 4,5]];



17                                                        1/6/2012
Introduction to JavaScript (cont.)
      Array op:




18                                   1/6/2012
Introduction to JavaScript (cont.)
      If Statement:         if ( condition1 ) {
                                    // door #1
                             } else if (condition2) {
                                    // door #2
                             } else {
                                    // door #3
                             }
      Switch Statement:
       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
19                                                            1/6/2012
       }
Introduction to JavaScript (cont.)
  While Statement:
        while (condition) {
               // javascript to repeat
        }
  Do while Statement:
        do {
                 // javascript to repeat
        } while (condition) ;
  For Statement:
       for (var count = 0; count < MaxLoop; count++){
             // javascript to repeat
       }

20                                               1/6/2012
Introduction to JavaScript (cont’)
  Break Statement:
        while (condition) {
               // javascript to repeat
               if (i==3){
                      break;
               }
        }
  Continue Statement:
        do {
                if (i==3){
                      continue;
                }
        } while (condition) ;
  For in Statement:
        for (variable in object){
               code to be executed
        }
21                                       1/6/2012
Introduction to JavaScript (cont.)
      Function:
           function functionName(parameters){
                 // the JavaScript you want to run
                 return value;
           }
      Anonymous function: (lambda function)
           function (parameter1, parameter2){
                 // the JavaScript you want to run
                 return value;
           }

22                                                   1/6/2012
Introduction to JavaScript (cont.)
      Global vs. local variable:
            var paramenter = 3;
            function func1(){
                      alert(parameter); // alert(3)
                      var parameter = 5;
                      alert(parameter); // alert(5)
            }
            func1();
      Try, catch, throws:
              try{
                       //Run some code here
                       throw ‚Error‛;
              }
              catch(err)
              {
                     //Handle errors here
              }
      Put variable as a reference definitions at the beginning of your script
23                                                                       1/6/2012
How to work with JavaScript?
      Work with String:
        Determine length of a string: strVar.length
        Changing case of a string: strVar.toUpperCase()
            or strVar.toLowerCase()
        Searching String: strVar.indexOf(‘strSearch’)




        Extract part of a String:
       strVar.slice(start, [end])



24                                                     1/6/2012
How to work with JavaScript? (cont.)
      Work with Regular Expression:




25                                     1/6/2012
How to work with JavaScript? (cont.)
      Work with Regular Expression:
        Useful Regex:
          U.S. Zip code:


          U.S. Phone #:


          Email Address:


          Date:


          Web Address:



26                                     1/6/2012
How to work with JavaScript? (cont.)
      Work with Number:
        JavaScript interpreter usually converts a string to a
        number when it seems like a number is called for. For
        example:                but:

        Number():



        ParseInt():


        ParseFloat():


        Test a Number:



27                                                               1/6/2012
How to work with JavaScript? (cont.)
      Work with Number (next):
        Math.round(), Math.ceil(), Math.floor():


        Formatting currency:


        Creating Random number:


          Selecting random number:




          Selecting randomly element of array:



28                                                  1/6/2012
How to work with JavaScript? (cont.)
      Work with Dates and Times:
        Declare:




29                                  1/6/2012
How to work with JavaScript? (cont.)
      Work with Dates and Times (next):
        Getting the month:




        Getting the Day of a week:




        Creating Day other than today:



30                                         1/6/2012
How to work with JavaScript? (cont.)
      Work with Dates and Times (next):
        Getting the time format (e.g.: 12:03:59 a.m.):




31                                                        1/6/2012
TRAINING JAVASCRIPT & jQUERY

    Editor: Nguyễn Đức Minh Khôi
Email: nguyenducminhkhoi@gmail.com
   HCMC University of Technology
             @Jan, 2012
Content
        Introduction to JavaScript

           JavaScript – the basic

            Getting Started with jQuery

           jQuery in Action

        Ajax, tips, tricks

33                                        1/6/2012
Part3:Getting Started with jQuery

       Selecting Element of a page


       Attach an Event to Elements


       Response Events by doing sth


34                                    1/6/2012
Introduction to jQuery
      Why use jQuery?
          Relatively small file size
          Friendly to web designers
          It’s tried and true
          It’s free
          Large developer community
          Plugins
      How to use?
        Link to jQuery file on CDN server:
           <script src=
           "http://ajax.googleapis.com/ajax/libs/jquery/1.6.3
       /jquery.m in.js"></script>
        Download jQuery file:
           http://docs.jquery.com/Downloading_jQuery.
              <script src="js/jquery-1.6.3.min.js"></script>
35                                                         1/6/2012
Introduction to jQuery (cont.)
      Some useful jQuery plugin:
        jQuery-color: https://github.com/jquery/jquery-color
        jQuery-easing: http://gsgd.co.uk/sandbox/jquery/easing/
        JQuery-fancybox: http://fancybox.net/
        JQuery-scrollTo: http://plug-ins.jquery.com/project/ScrollTo
        jQuery-navigation: www.pollenizer.com/jquery-navigation-plugin/
        jQuery-UI: http://jqueryui.com/download
        jQuery-qTip: http://craigsworks.com/projects/qtip2/
        jQuery Raty - A Star Rating: http://www.wbotelhos.com/raty/
        jQuery Flickr: http://johnpatrickgiven.com/jquery/flickr-gallery/
        jQuery-Ajax Form plugins: http://jquery.malsup.com/form/
        jQuery-Ajax Autocomplete: http://jqueryui.com/demos/auto-
         complete/
        jQuery-Ajax Uploadfile: http://www.uploadify.com/download/
        jQuery-Ajax twitter: http://tweet.seaofclouds.com/
36
        jQuery-Ajax Google Map: http://www.pittss.lv/jquery/gomap/ 1/6/2012
Selecting Element of a page
      Notes:
        put your JavaScript programming (all your <script> tags) after any
         other content inside the <head> tag, but before the closing </head>
         tag.
           <script>
                   $(document).ready(function() {
                            // your programming goes here
                   }); // end ready
            </script>
         Or use for short:
           <script>
                   $(function() {
                            // your programming goes here
                   }); // end ready
37          </script>                                                   1/6/2012
Selecting Element of a page (cont.)




38                                   1/6/2012
39   1/6/2012
40   1/6/2012
Selecting Element of a page (cont.)
      Select page element (examples)
        Basic Selector (like CSS selector)
           Id selector: var messagePara = $('#message');
           Tag selector: var linksList = $('a');
           Class selector: var a = $('.submenu');
        Advanced Selector
           Descendent selector: $('#navBar a')
           Child selector: $(‘body > p')
           Adjacent sibling selector: $('h2 + div')
           Attribute selector: $('img[alt]')
        jQuery filter
           $('p:first'); $('p:last'); $('p:odd');
            $('p:even');
           $('a:not(.navButton)'); $('li:has(a)');
           $('a:contains(Click Me!)');
           $('div:hidden').show(); $('div:visible').show();

41                                                       1/6/2012
Selecting Element of a page (cont.)
      jQuery selection principles
        Automatic loops: $('#slideshow img').hide();
        Chaining function: $('#popUp').width(300).height(300);
      Useful functions:




42                                                         1/6/2012
43   1/6/2012
44   1/6/2012
45   1/6/2012
Selecting Element of a page (cont.)
 $('#errors').html();
 $('#errors').html('<p>There are four errors in this form</p>');
 $('#errors h2').text('No errors found');
 $('#errors').append('<p>There are four errors in this form</p>');
 $('#errors').prepend('<p>There are four errors in this
     form</p>');
 $('#userName').after('<span class="error">User name
     required</span>');
 $('#product101').replaceWith(<p>Added to cart</p>');
 $('a[href^="http://"]').addClass('externalLink');
 $('#alertBox').removeClass('highlight');
 $('body').toggleClass('altStyle');
 $('#main').css('background-color');
 $('body').css('font-size', '200%');
 var imageFile = $('#banner img').attr('src');

46   $('body').removeAttr('bgColor');                       1/6/2012
Selecting Element of a page (cont.)
      Notes:
        Changing Multiple CSS Properties at Once




        Each function:




                                                    $(this): element
                                                    loop through all
                                                    elements.

47                                                            1/6/2012
Attach an Event to Elements
      Types of events:




48                                   1/6/2012
49   1/6/2012
50   1/6/2012
51   1/6/2012
Attach an Event to Elements (cont)
      Using Event – the jQuery Way:




52                                     1/6/2012
Attach an Event to Elements- e.g.




53                                   1/6/2012
Response Events by doing sth
      jQuery Effects:




54                                  1/6/2012
Response Events by doing sth (cont.)
      Examples:




55                                  1/6/2012
Response Events by doing sth (cont.)
      jQuery Animations:
        Some attr are built-in (no need plugins)
        Some attr need plugins:
          jquery-color: https://github.com/jquery/jquery-color
          jquery-easing: http://gsgd.co.uk/sandbox/jquery/easing/
          How to use:




56                                                                   1/6/2012
Response Events by doing sth (cont.)
       Notes:
         with hyphens: in CSS use 1 of these:




         can use += or -= in CSS attr:




         No use shorthands:

57                                               1/6/2012
Response Events by doing sth (cont.)
      Using Easing:




      Callback function: a
       function that runs
       only after the effect
       is completed.


58                                  1/6/2012
TRAINING JAVASCRIPT & jQUERY

    Editor: Nguyễn Đức Minh Khôi
Email: nguyenducminhkhoi@gmail.com
   HCMC University of Technology
             @Jan, 2012
Content
        Introduction to JavaScript

           JavaScript – the basic

            Getting Started with jQuery

           jQuery in Action

        Ajax, tips, tricks

60                                        1/6/2012
Part3: jQuery in Action
       Improving your images

       Improving navigation

       Enhancing Web forms

       Expanding your interfaces

61                                 1/6/2012
jQuery in Action
      Notes:
        var newPara = $(‘<p>Hello</p>’) creates a new
         paragraph tag containing the word Hello.
        var $banner = $('#banner');
             The dollar sign reminds you that the variable holds a
             jQuery selection and not just any old value like a number
             or a string.
        This part is just giving you some basic techniques to do with
         jQuery, for more information, you should lookup some
         tutorial in the main reference book “Java-jQuery the Missing
         Manual” - Part 3. This will give you more clearly about this
         techniques. And practice some tutorials in this books for
         conquer the idea.
        You should download and see the usage of the plugins in
         listed in the slide #34 of this slides.

62                                                               1/6/2012
Improving your images
      Changing an Image’s src Attribute:

                                     tells the web browser to actually
                                     download the new image




      Preloading Images




63                                                             1/6/2012
Improving your images (cont.)
      Rollover images:
        Just an image swap triggered by the mouse moving over
        an image




64                                                       1/6/2012
Improving navigation
      Open External links in new Windows:


        location.protocol stores the object’s protocol property like http or https
        location.hostname stores the object’s host name like www.google.com
        The not() function is a useful way of excluding some elements from a jQuery
         selection
      Creating new Windows:

        to close:




65                                                                               1/6/2012
Improving navigation (cont.)
      Opening page within a page – fancy box plugin




      Navigation Bar Plugin




66                                                     1/6/2012
Enhancing Web Forms
      Getting and Setting Form value Element:

        Determining Whether Buttons and Boxes Are Checked




                                                         Don’t do that or
                                                         not follow that
                                                              links
      Form events:
        Submit: validate
       Username is input


67                                                               1/6/2012
Enhancing Web Forms (Cont.)
       Focus: (input text, default value will disappear)




       Blur: (check recently input box is correct)




       Click:


       Change:

68                                                          1/6/2012
Enhancing Web Forms (cont.)
      Adding smart to your form:
        Focus the first field in the form:



        Disabling and Enabling Fields:



        Hiding and Showing form option:




69                                            1/6/2012
Enhancing Web Forms (cont.)
      Form validation plugin
      Basic validation:
        Adding validation rules:


        Adding Error message:




      Advanced validation: (see more at the book)




70                                                   1/6/2012
Expanding your Interface
      Organizing Information in Tabbed Panel
      Adding a Content Slider to Your site
      Determining the Size and Position of Page Element
      Adding Tooltips
      (See more at the book)




71                                                    1/6/2012
TRAINING JAVASCRIPT & jQUERY

    Editor: Nguyễn Đức Minh Khôi
Email: nguyenducminhkhoi@gmail.com
   HCMC University of Technology
             @Jan, 2012
Content
        Introduction to JavaScript

           JavaScript – the basic

            Getting Started with JQuery

           JQuery in Action

        Ajax, tips, tricks

73                                        1/6/2012
Part3:Ajax, Tips and Tricks
     What is Ajax?


     JSON


     Tips and tricks


74                                 1/6/2012
What is Ajax?
      stands for Asynchronous JavaScript and XML
      not an “official” technology like HTML, JavaScript, or CSS.
      refers to the interaction of a mix of technologies—JavaScript,
       the web browser, and the web server—to retrieve and display
       new content without loading a new web page
      What you can do with Ajax:
        Display new HTML content without reloading the page
        Submit a form and instantly display results
        Log in without leaving the page
        Star-rating widget
        Browsing through database information.


75                                                             1/6/2012
What is Ajax? (cont.)
      Know more about web server:
        Web server: stores documents and when a web browser
         asks for a document, the web server delivers it. (Apache,
         IIS,…)
        Web application: understands a server-side
         programming language like PHP, Java, Ruby, Python.
         perform tasks that aren’t possible with only an HTML
         page, like sending email, storing information in a
         database.
        Web database: store information like the names and
         addresses of customers, details of products you sell, or
         an archive of your favorite recipes. (e.g.: MySQL,
         PostgreSQL, SQL Server…

76                                                          1/6/2012
What is Ajax? (cont.)
      How does Ajax work?




77                           1/6/2012
What is Ajax? (cont.)
      Ajax talks with sever:
        Create an instance of the XMLHttpRequest object.
            var newXHR = new XMLHttpRequest();
        Use the XHR’s open() method to specify what kind of
         data you’ll send and where the data will go
            newXHR.open('GET', 'shop.php?productID=34');
        Create a function to handle the results: use callback
         function
        Send the request
            newXHR.send('q=javascript');
        Receive the response

78                                                           1/6/2012
What is Ajax? (cont.)
      Ajax – the jQuery way:




79                              1/6/2012
What is Ajax? (cont.)
      Ajax – the jQuery way:
        Use .load() function:


          Use: get HTML from a web server and inject it into a page.
          Notes: Just use root-relative links, or make sure the file you load is
           located in the same directory as the page that’s using the load()
           function.
        Use .get() and .post() function:



          When you get(): when you want to get information, like requesting
           the price of a particular product or obtaining a list of most popular
           products.
          When use post(): when sending data that will change information
           on the server, like a request to delete a file, update a database, or
80         insert new information into a database.                           1/6/2012
What is Ajax? (cont.)
       Query String:
         Notes: have to escape and encode query string, like:




       Object Literal:



       jQuery Serialize function(): collects all of the field names and the
        values currently in each field and creates a single query string.

       Processing data from Server:




       Handling Error:
81                                                                          1/6/2012
What is Ajax? (cont.)




                             data could be plain
                             text, HTML, XML,
                             or JSON

82                                         1/6/2012
JSON
      Stands for JavaScript Object Notation
      is usually better than XML;
      JSON is JavaScript, it works quickly and easily in
       JavaScript program.




      getJSON() function:




83                                                          1/6/2012
JSON (cont.)
      Access JSON Data:
        Simple data:




        Complex data:




84                         1/6/2012
JSONP
      b/c Ajax requests are limited to the same domain.
      stands for JSON with padding. provides one way to
       retrieve information from another site.
      Ajax request of the foreign site, you load a script that
       contains the JSON code in it. Or linking to an external
       JavaScript file on Google.
      For example:




85                                                         1/6/2012
Tips and tricks
      Useful tips:
        $() Is the Same as jQuery()
                                     like
        Saving selections into variables



          Or use chaining:


          Instead of :



          Putting reference in variable:

86                                          1/6/2012
Tips and tricks (cont.)
      Adding contents few times as possible

                                                        NOT



        Use:




      Optimize your selector:
        Use ID selectors if at all possible.
        Use IDs first, as part of a descendent selector.
        Use find function:

87                                                            1/6/2012
Tips and tricks (cont.)
      Using the jQuery docs efficiently:
       http://docs.jquery.com/ (especially the jQuery API)
      Compress your JavaScript and other file before deploy
       your website:
       http://developer.yahoo.com/yui/compressor
      Use firebug – Firefox plugin debugger efficiently
       http://www.youtube.com/watch?v=1rfiPaWz4No
      jQuery plugin site: http://plugins.jquery.com/
      jQuery UI site: http://jqueryui.com



88                                                      1/6/2012
Conclusion
      JavaScript is great, but it is also
         difficult for you to conquer, you
         should use jQuery instead!
        jQuery isn’t only about simpler code and being more
         productive.
        It is also about great community, support, tutorials,
         plugins, open (free) license, test coverage books,
         speed, light weight code
        Keep the jQuery cheat sheet beside you when working
         with jQuery
        Practice the tutorial in main reference book!
89                                                      1/6/2012
References
      JavaScript and jQuery the missing manual, 2nd Edition
       2011- David Sawyer McFarland
      JavaScript 1.6 Visual Cheat Sheet




     Suggest Reading
      jQuery in Actions by Bear Bibeault and Yehuda Katz
      Head First JavaScript by Michael Morrison (O’Reilly)



90                                                      1/6/2012
Thanks for your watching!

    Editor: Nguyễn Đức Minh Khôi
Email: nguyenducminhkhoi@gmail.com

More Related Content

What's hot

An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScript
tonyh1
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
ch samaram
 
Using Grails to power your electric car
Using Grails to power your electric carUsing Grails to power your electric car
Using Grails to power your electric car
Marco Pas
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy
 

What's hot (20)

An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScript
 
Java script
Java scriptJava script
Java script
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
AngularJS - A JavaScript Framework
AngularJS - A JavaScript FrameworkAngularJS - A JavaScript Framework
AngularJS - A JavaScript Framework
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Introduction to Javascript By Satyen
Introduction to Javascript By  SatyenIntroduction to Javascript By  Satyen
Introduction to Javascript By Satyen
 
Java script
Java scriptJava script
Java script
 
Using Grails to power your electric car
Using Grails to power your electric carUsing Grails to power your electric car
Using Grails to power your electric car
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
 
Java scripts
Java scriptsJava scripts
Java scripts
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Java script final presentation
Java script final presentationJava script final presentation
Java script final presentation
 
Java script
Java scriptJava script
Java script
 
Java script
Java scriptJava script
Java script
 
Java script Session No 1
Java script Session No 1Java script Session No 1
Java script Session No 1
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Java script
Java scriptJava script
Java script
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentals
 

Viewers also liked

Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt NamMột góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Imr Hung
 
Software Development Process Seminar at HUI
Software Development Process Seminar at HUISoftware Development Process Seminar at HUI
Software Development Process Seminar at HUI
KMS Technology
 

Viewers also liked (20)

Wordnet Introduction
Wordnet IntroductionWordnet Introduction
Wordnet Introduction
 
Training Google Drive and Hangouts.pptx
Training Google Drive and Hangouts.pptxTraining Google Drive and Hangouts.pptx
Training Google Drive and Hangouts.pptx
 
Training basic latex
Training basic latexTraining basic latex
Training basic latex
 
Ubuntu – Linux Useful Commands
Ubuntu – Linux Useful CommandsUbuntu – Linux Useful Commands
Ubuntu – Linux Useful Commands
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
Gioi thieu truong bk
Gioi thieu truong bkGioi thieu truong bk
Gioi thieu truong bk
 
SEASR and UIMA
SEASR and UIMASEASR and UIMA
SEASR and UIMA
 
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt NamMột góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
Một góc nhìn về chuyện khởi nghiệp của Sinh Viên Việt Nam
 
Training android
Training androidTraining android
Training android
 
Introduction to WEB HTML, CSS
Introduction to WEB HTML, CSSIntroduction to WEB HTML, CSS
Introduction to WEB HTML, CSS
 
Software Development Process Seminar at HUI
Software Development Process Seminar at HUISoftware Development Process Seminar at HUI
Software Development Process Seminar at HUI
 
Wordnet
WordnetWordnet
Wordnet
 
Pbc day-01-introduction
Pbc day-01-introductionPbc day-01-introduction
Pbc day-01-introduction
 
An Introduction of Apache Hadoop
An Introduction of Apache HadoopAn Introduction of Apache Hadoop
An Introduction of Apache Hadoop
 
Git Using - pythonvietnam.info
Git Using - pythonvietnam.infoGit Using - pythonvietnam.info
Git Using - pythonvietnam.info
 
Python Beginner Class day-03-flow
Python Beginner Class day-03-flowPython Beginner Class day-03-flow
Python Beginner Class day-03-flow
 
Slide Python Bai 2 pythonvietnam.info
Slide Python Bai 2   pythonvietnam.infoSlide Python Bai 2   pythonvietnam.info
Slide Python Bai 2 pythonvietnam.info
 
Bai 1 pythonvietnam.info
Bai 1   pythonvietnam.infoBai 1   pythonvietnam.info
Bai 1 pythonvietnam.info
 
Python Beginner Class day-07-08-module
Python Beginner Class day-07-08-modulePython Beginner Class day-07-08-module
Python Beginner Class day-07-08-module
 
Design patterns tutorials
Design patterns tutorialsDesign patterns tutorials
Design patterns tutorials
 

Similar to Training javascript 2012 hcmut

JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
Laurence Svekis ✔
 
JavaScript and AJAX
JavaScript and AJAXJavaScript and AJAX
JavaScript and AJAX
Frane Bandov
 
Isomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master ClassIsomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master Class
Spike Brehm
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 

Similar to Training javascript 2012 hcmut (20)

8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation8.-Javascript-report powerpoint presentation
8.-Javascript-report powerpoint presentation
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015The curious Life of JavaScript - Talk at SI-SE 2015
The curious Life of JavaScript - Talk at SI-SE 2015
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Java scriptforjavadev part1
Java scriptforjavadev part1Java scriptforjavadev part1
Java scriptforjavadev part1
 
JS Class 2016
JS Class 2016JS Class 2016
JS Class 2016
 
JS class slides (2016)
JS class slides (2016)JS class slides (2016)
JS class slides (2016)
 
What's new in DWR version 3
What's new in DWR version 3What's new in DWR version 3
What's new in DWR version 3
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial Handouts
 
Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1Lecture 5: Client Side Programming 1
Lecture 5: Client Side Programming 1
 
JavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript HereJavaScript Core fundamentals - Learn JavaScript Here
JavaScript Core fundamentals - Learn JavaScript Here
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
JavaScript and AJAX
JavaScript and AJAXJavaScript and AJAX
JavaScript and AJAX
 
Java script Basic
Java script BasicJava script Basic
Java script Basic
 
Java scipt
Java sciptJava scipt
Java scipt
 
Isomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master ClassIsomorphic JavaScript: #DevBeat Master Class
Isomorphic JavaScript: #DevBeat Master Class
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Nodejs
NodejsNodejs
Nodejs
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 

More from University of Technology (10)

Phương pháp học đại học
Phương pháp học đại họcPhương pháp học đại học
Phương pháp học đại học
 
Basic probability & statistics
Basic probability & statisticsBasic probability & statistics
Basic probability & statistics
 
Introduction to gsa vietnam
Introduction to gsa vietnamIntroduction to gsa vietnam
Introduction to gsa vietnam
 
Phuong phap hoc tap on thi 2013
Phuong phap hoc tap on thi 2013Phuong phap hoc tap on thi 2013
Phuong phap hoc tap on thi 2013
 
Training python (new Updated)
Training python (new Updated)Training python (new Updated)
Training python (new Updated)
 
Phương pháp học tập official
Phương pháp học tập officialPhương pháp học tập official
Phương pháp học tập official
 
English Writing Skills
English Writing SkillsEnglish Writing Skills
English Writing Skills
 
Django - basics
Django - basicsDjango - basics
Django - basics
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Presentation bkit business
Presentation bkit businessPresentation bkit business
Presentation bkit business
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

Training javascript 2012 hcmut

  • 1. TRAINING JAVASCRIPT & jQUERY Editor: Nguyễn Đức Minh Khôi Email: nguyenducminhkhoi@gmail.com HCMC University of Technology @Jan, 2012
  • 2. Content Introduction to JavaScript JavaScript – the basic Getting Started with JQuery JQuery in Action Ajax, tips, tricks 2 1/6/2012
  • 3. Part1: Introduction to JavaScript What is JavaScript and JQuery? The Web World Software for JavaScript programming 3 1/6/2012
  • 4. What is JavaScript?  JavaScript is a programming language that lets you supercharge your HTML with animation, interactivity, and dynamic visual effects. 4 1/6/2012
  • 5. What is jQuery?  jQuery is a JavaScript library intended to make JavaScript programming easier and more fun.  solves the two biggest headaches with JavaScript— complexity and the finicky nature of different web browsers.  you can add advanced features to your website with thousands of easy-to-use jQuery plug-ins. 5 1/6/2012
  • 6. The web world  HTML provides the structural layer, organizing content like pictures and words in a meaningful way  CSS (Cascading Style Sheets) provides the presentational layer, making the content in the HTML look good  JavaScript adds a behavioral layer, bringing a web page to life so it interacts with web visitors and reduce “stress” for Server.  Other Server Scripting: PHP, ASP, JSP, Ruby, Python… do the main part of your project! 6 1/6/2012
  • 7. Software for JS Programming  Notepad++ (Windows, http://notepad-plus-plus.org) is a coder’s friend.  Netbeans (Windows, Linux, Mac; www.eclipse.org) is a free, popular choice amongst Java Developers, but includes tools for working with HTML, CSS, and JavaScript.  Eclipse and Aptana Studio plugin (Windows, Linux, Mac; www.aptana.org) is a powerful, free coding environment with tools for working with HTML, CSS, JavaScript, PHP, and Ruby on Rails.  Dreamweaver (Mac and Windows, www.adobe.com/products/dreamweaver.html) is a visual web page editor.  Expression Web Designer (Windows, www.microsoft.com/expression/products/StudioWebPro_ Overview.aspx) is Microsoft’s entry in the web design field. 7 1/6/2012
  • 8. Software for JS Programming (cont’)  Google Chrome browser and Developer tools (Ctr + Shift + J)  Firefox and firebug plugin (http://getfirebug.com/)  Internet Explorer 9 – console (F12)  Safari and Error console (Ctrl + Alt + C)  Wamp Server (for Ajax practice) for windows www.wampserver.com/en/  Lamp Server for Linux (Debian, Ubuntu) http://www.sph.umich.edu/csg/abecasis/LAMP/downl oad/  Mamp Server for Mac: www.mamp.info/en 8 1/6/2012
  • 9. TRAINING JAVASCRIPT & jQUERY Editor: Nguyễn Đức Minh Khôi Email: nguyenducminhkhoi@gmail.com HCMC University of Technology @Jan, 2012
  • 10. Content Introduction to JavaScript JavaScript – the basic Getting Started with JQuery JQuery in Action Ajax, tips, tricks 10 1/6/2012
  • 11. Part2: JavaScript – the Basics Introduction to JavaScript How to work with JavaScript 11 1/6/2012
  • 12. Introduction to JavaScript  How to add JS to a page: Notes: if you use HTML earlier than HTML5 should: 12 1/6/2012
  • 13. Introduction to JavaScript (cont.)  URL type:  Absolute path:  http://www.cosmofarmer.com/scripts/site.js  Use when you point to a file that’s not on the same server as the your web page.  Root relative:  /scripts/site.js  Use for JavaScript files stored on your own site.  Document relative:  ../scripts/site.js - ../ means climb up out of the folder  Use when you’re designing on your own computer without the aid of a web server. 13 1/6/2012
  • 14. Introduction to JavaScript (cont.)  JS is a client-side language which means that it works inside a web browser.  JS is also a scripting language like PHP, Ruby, Python ColdFusion as well.  JS is a multi-paradigm language, supporting object- oriented, imperative, and functional programming styles.  JavaScript was formalized in the ECMAScript language standard.  JavaScript uses syntax influenced by that of C. And very different sematic with Java.  See more at http://www.w3schools.com/js/default.asp 14 1/6/2012
  • 15. Introduction to JavaScript (cont.)  Statement  Basic programming unit  E.g.: alert('Hello World!');  Popup Box:  alert(‚Be alert‛) // alert something with user  prompt(‚enter sth‛)//ask user to input something  confirm("Press a button!");  Built in function  document.write() //add content to a page  isNaN(variable) //check if variable is a number  Number(variable) // convert to number or NaN  String(variable) // convert to string  Data Type  Number: 5, 5.125, NaN (just– Double)  String: ‘Hello’, ‚Hello‛, ‚Hello ’World’ !‛, ‚’a‛, ‚Hello‛World‛!‛  Boolean: true, false  Object 15  null, undefined 1/6/2012
  • 16. Introduction to JavaScript (cont.)  Variable  Declare: var + varName;  Name: abc ≠ Abc, $abc, _abc, a123, 1bcd, alert  Assign: varName = value;  Show values: alert(varName);  Operation:  Boolean op: ==, != , ===, !==, >, < , >=, <=, &&, ||, !  Number op: 3 + 4, 3 / 4, 3 * 4, 3 – 4  String op: ‘abc’ + ‘def’;  Mix: ‘12’ + 4 = ‘124’; +’123’ + 4 = 127; Number(‘123’) + 4 = 127; ‘12’ * 4 = 48;  Complex op: ++, --, *=, /=, +=, -=  Ternary op: (condition) ? A : B 16 1/6/2012
  • 17. Introduction to JavaScript (cont.)  Comment:  //this is a comment inline  /* something to comment in many lines */  Array (List in real)  Declare: var arr = [1, 2, 3]; or var arr = new Array(1, 2, 3);  Access: arr[0];  Notes:  Empty array: var arr = [];  Mix types: var arr = [1, 2, ‘abc’, true, [3, 4,5]]; 17 1/6/2012
  • 18. Introduction to JavaScript (cont.)  Array op: 18 1/6/2012
  • 19. Introduction to JavaScript (cont.)  If Statement: if ( condition1 ) { // door #1 } else if (condition2) { // door #2 } else { // door #3 }  Switch Statement: 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 19 1/6/2012 }
  • 20. Introduction to JavaScript (cont.)  While Statement: while (condition) { // javascript to repeat }  Do while Statement: do { // javascript to repeat } while (condition) ;  For Statement: for (var count = 0; count < MaxLoop; count++){ // javascript to repeat } 20 1/6/2012
  • 21. Introduction to JavaScript (cont’)  Break Statement: while (condition) { // javascript to repeat if (i==3){ break; } }  Continue Statement: do { if (i==3){ continue; } } while (condition) ;  For in Statement: for (variable in object){ code to be executed } 21 1/6/2012
  • 22. Introduction to JavaScript (cont.)  Function: function functionName(parameters){ // the JavaScript you want to run return value; }  Anonymous function: (lambda function) function (parameter1, parameter2){ // the JavaScript you want to run return value; } 22 1/6/2012
  • 23. Introduction to JavaScript (cont.)  Global vs. local variable: var paramenter = 3; function func1(){ alert(parameter); // alert(3) var parameter = 5; alert(parameter); // alert(5) } func1();  Try, catch, throws: try{ //Run some code here throw ‚Error‛; } catch(err) { //Handle errors here }  Put variable as a reference definitions at the beginning of your script 23 1/6/2012
  • 24. How to work with JavaScript?  Work with String:  Determine length of a string: strVar.length  Changing case of a string: strVar.toUpperCase() or strVar.toLowerCase()  Searching String: strVar.indexOf(‘strSearch’)  Extract part of a String: strVar.slice(start, [end]) 24 1/6/2012
  • 25. How to work with JavaScript? (cont.)  Work with Regular Expression: 25 1/6/2012
  • 26. How to work with JavaScript? (cont.)  Work with Regular Expression:  Useful Regex:  U.S. Zip code:  U.S. Phone #:  Email Address:  Date:  Web Address: 26 1/6/2012
  • 27. How to work with JavaScript? (cont.)  Work with Number:  JavaScript interpreter usually converts a string to a number when it seems like a number is called for. For example: but:  Number():  ParseInt():  ParseFloat():  Test a Number: 27 1/6/2012
  • 28. How to work with JavaScript? (cont.)  Work with Number (next):  Math.round(), Math.ceil(), Math.floor():  Formatting currency:  Creating Random number:  Selecting random number:  Selecting randomly element of array: 28 1/6/2012
  • 29. How to work with JavaScript? (cont.)  Work with Dates and Times:  Declare: 29 1/6/2012
  • 30. How to work with JavaScript? (cont.)  Work with Dates and Times (next):  Getting the month:  Getting the Day of a week:  Creating Day other than today: 30 1/6/2012
  • 31. How to work with JavaScript? (cont.)  Work with Dates and Times (next):  Getting the time format (e.g.: 12:03:59 a.m.): 31 1/6/2012
  • 32. TRAINING JAVASCRIPT & jQUERY Editor: Nguyễn Đức Minh Khôi Email: nguyenducminhkhoi@gmail.com HCMC University of Technology @Jan, 2012
  • 33. Content Introduction to JavaScript JavaScript – the basic Getting Started with jQuery jQuery in Action Ajax, tips, tricks 33 1/6/2012
  • 34. Part3:Getting Started with jQuery Selecting Element of a page Attach an Event to Elements Response Events by doing sth 34 1/6/2012
  • 35. Introduction to jQuery  Why use jQuery?  Relatively small file size  Friendly to web designers  It’s tried and true  It’s free  Large developer community  Plugins  How to use?  Link to jQuery file on CDN server: <script src= "http://ajax.googleapis.com/ajax/libs/jquery/1.6.3 /jquery.m in.js"></script>  Download jQuery file: http://docs.jquery.com/Downloading_jQuery. <script src="js/jquery-1.6.3.min.js"></script> 35 1/6/2012
  • 36. Introduction to jQuery (cont.)  Some useful jQuery plugin:  jQuery-color: https://github.com/jquery/jquery-color  jQuery-easing: http://gsgd.co.uk/sandbox/jquery/easing/  JQuery-fancybox: http://fancybox.net/  JQuery-scrollTo: http://plug-ins.jquery.com/project/ScrollTo  jQuery-navigation: www.pollenizer.com/jquery-navigation-plugin/  jQuery-UI: http://jqueryui.com/download  jQuery-qTip: http://craigsworks.com/projects/qtip2/  jQuery Raty - A Star Rating: http://www.wbotelhos.com/raty/  jQuery Flickr: http://johnpatrickgiven.com/jquery/flickr-gallery/  jQuery-Ajax Form plugins: http://jquery.malsup.com/form/  jQuery-Ajax Autocomplete: http://jqueryui.com/demos/auto- complete/  jQuery-Ajax Uploadfile: http://www.uploadify.com/download/  jQuery-Ajax twitter: http://tweet.seaofclouds.com/ 36  jQuery-Ajax Google Map: http://www.pittss.lv/jquery/gomap/ 1/6/2012
  • 37. Selecting Element of a page  Notes:  put your JavaScript programming (all your <script> tags) after any other content inside the <head> tag, but before the closing </head> tag.  <script> $(document).ready(function() { // your programming goes here }); // end ready </script> Or use for short:  <script> $(function() { // your programming goes here }); // end ready 37 </script> 1/6/2012
  • 38. Selecting Element of a page (cont.) 38 1/6/2012
  • 39. 39 1/6/2012
  • 40. 40 1/6/2012
  • 41. Selecting Element of a page (cont.)  Select page element (examples)  Basic Selector (like CSS selector)  Id selector: var messagePara = $('#message');  Tag selector: var linksList = $('a');  Class selector: var a = $('.submenu');  Advanced Selector  Descendent selector: $('#navBar a')  Child selector: $(‘body > p')  Adjacent sibling selector: $('h2 + div')  Attribute selector: $('img[alt]')  jQuery filter  $('p:first'); $('p:last'); $('p:odd'); $('p:even');  $('a:not(.navButton)'); $('li:has(a)');  $('a:contains(Click Me!)');  $('div:hidden').show(); $('div:visible').show(); 41 1/6/2012
  • 42. Selecting Element of a page (cont.)  jQuery selection principles  Automatic loops: $('#slideshow img').hide();  Chaining function: $('#popUp').width(300).height(300);  Useful functions: 42 1/6/2012
  • 43. 43 1/6/2012
  • 44. 44 1/6/2012
  • 45. 45 1/6/2012
  • 46. Selecting Element of a page (cont.)  $('#errors').html();  $('#errors').html('<p>There are four errors in this form</p>');  $('#errors h2').text('No errors found');  $('#errors').append('<p>There are four errors in this form</p>');  $('#errors').prepend('<p>There are four errors in this form</p>');  $('#userName').after('<span class="error">User name required</span>');  $('#product101').replaceWith(<p>Added to cart</p>');  $('a[href^="http://"]').addClass('externalLink');  $('#alertBox').removeClass('highlight');  $('body').toggleClass('altStyle');  $('#main').css('background-color');  $('body').css('font-size', '200%');  var imageFile = $('#banner img').attr('src');  46 $('body').removeAttr('bgColor'); 1/6/2012
  • 47. Selecting Element of a page (cont.)  Notes:  Changing Multiple CSS Properties at Once  Each function: $(this): element loop through all elements. 47 1/6/2012
  • 48. Attach an Event to Elements  Types of events: 48 1/6/2012
  • 49. 49 1/6/2012
  • 50. 50 1/6/2012
  • 51. 51 1/6/2012
  • 52. Attach an Event to Elements (cont)  Using Event – the jQuery Way: 52 1/6/2012
  • 53. Attach an Event to Elements- e.g. 53 1/6/2012
  • 54. Response Events by doing sth  jQuery Effects: 54 1/6/2012
  • 55. Response Events by doing sth (cont.)  Examples: 55 1/6/2012
  • 56. Response Events by doing sth (cont.)  jQuery Animations:  Some attr are built-in (no need plugins)  Some attr need plugins:  jquery-color: https://github.com/jquery/jquery-color  jquery-easing: http://gsgd.co.uk/sandbox/jquery/easing/  How to use: 56 1/6/2012
  • 57. Response Events by doing sth (cont.)  Notes:  with hyphens: in CSS use 1 of these:  can use += or -= in CSS attr:  No use shorthands: 57 1/6/2012
  • 58. Response Events by doing sth (cont.)  Using Easing:  Callback function: a function that runs only after the effect is completed. 58 1/6/2012
  • 59. TRAINING JAVASCRIPT & jQUERY Editor: Nguyễn Đức Minh Khôi Email: nguyenducminhkhoi@gmail.com HCMC University of Technology @Jan, 2012
  • 60. Content Introduction to JavaScript JavaScript – the basic Getting Started with jQuery jQuery in Action Ajax, tips, tricks 60 1/6/2012
  • 61. Part3: jQuery in Action Improving your images Improving navigation Enhancing Web forms Expanding your interfaces 61 1/6/2012
  • 62. jQuery in Action  Notes:  var newPara = $(‘<p>Hello</p>’) creates a new paragraph tag containing the word Hello.  var $banner = $('#banner'); The dollar sign reminds you that the variable holds a jQuery selection and not just any old value like a number or a string.  This part is just giving you some basic techniques to do with jQuery, for more information, you should lookup some tutorial in the main reference book “Java-jQuery the Missing Manual” - Part 3. This will give you more clearly about this techniques. And practice some tutorials in this books for conquer the idea.  You should download and see the usage of the plugins in listed in the slide #34 of this slides. 62 1/6/2012
  • 63. Improving your images  Changing an Image’s src Attribute: tells the web browser to actually download the new image  Preloading Images 63 1/6/2012
  • 64. Improving your images (cont.)  Rollover images:  Just an image swap triggered by the mouse moving over an image 64 1/6/2012
  • 65. Improving navigation  Open External links in new Windows:  location.protocol stores the object’s protocol property like http or https  location.hostname stores the object’s host name like www.google.com  The not() function is a useful way of excluding some elements from a jQuery selection  Creating new Windows:  to close: 65 1/6/2012
  • 66. Improving navigation (cont.)  Opening page within a page – fancy box plugin  Navigation Bar Plugin 66 1/6/2012
  • 67. Enhancing Web Forms  Getting and Setting Form value Element:  Determining Whether Buttons and Boxes Are Checked Don’t do that or not follow that links  Form events:  Submit: validate Username is input 67 1/6/2012
  • 68. Enhancing Web Forms (Cont.)  Focus: (input text, default value will disappear)  Blur: (check recently input box is correct)  Click:  Change: 68 1/6/2012
  • 69. Enhancing Web Forms (cont.)  Adding smart to your form:  Focus the first field in the form:  Disabling and Enabling Fields:  Hiding and Showing form option: 69 1/6/2012
  • 70. Enhancing Web Forms (cont.)  Form validation plugin  Basic validation:  Adding validation rules:  Adding Error message:  Advanced validation: (see more at the book) 70 1/6/2012
  • 71. Expanding your Interface  Organizing Information in Tabbed Panel  Adding a Content Slider to Your site  Determining the Size and Position of Page Element  Adding Tooltips  (See more at the book) 71 1/6/2012
  • 72. TRAINING JAVASCRIPT & jQUERY Editor: Nguyễn Đức Minh Khôi Email: nguyenducminhkhoi@gmail.com HCMC University of Technology @Jan, 2012
  • 73. Content Introduction to JavaScript JavaScript – the basic Getting Started with JQuery JQuery in Action Ajax, tips, tricks 73 1/6/2012
  • 74. Part3:Ajax, Tips and Tricks What is Ajax? JSON Tips and tricks 74 1/6/2012
  • 75. What is Ajax?  stands for Asynchronous JavaScript and XML  not an “official” technology like HTML, JavaScript, or CSS.  refers to the interaction of a mix of technologies—JavaScript, the web browser, and the web server—to retrieve and display new content without loading a new web page  What you can do with Ajax:  Display new HTML content without reloading the page  Submit a form and instantly display results  Log in without leaving the page  Star-rating widget  Browsing through database information. 75 1/6/2012
  • 76. What is Ajax? (cont.)  Know more about web server:  Web server: stores documents and when a web browser asks for a document, the web server delivers it. (Apache, IIS,…)  Web application: understands a server-side programming language like PHP, Java, Ruby, Python. perform tasks that aren’t possible with only an HTML page, like sending email, storing information in a database.  Web database: store information like the names and addresses of customers, details of products you sell, or an archive of your favorite recipes. (e.g.: MySQL, PostgreSQL, SQL Server… 76 1/6/2012
  • 77. What is Ajax? (cont.)  How does Ajax work? 77 1/6/2012
  • 78. What is Ajax? (cont.)  Ajax talks with sever:  Create an instance of the XMLHttpRequest object. var newXHR = new XMLHttpRequest();  Use the XHR’s open() method to specify what kind of data you’ll send and where the data will go newXHR.open('GET', 'shop.php?productID=34');  Create a function to handle the results: use callback function  Send the request newXHR.send('q=javascript');  Receive the response 78 1/6/2012
  • 79. What is Ajax? (cont.)  Ajax – the jQuery way: 79 1/6/2012
  • 80. What is Ajax? (cont.)  Ajax – the jQuery way:  Use .load() function:  Use: get HTML from a web server and inject it into a page.  Notes: Just use root-relative links, or make sure the file you load is located in the same directory as the page that’s using the load() function.  Use .get() and .post() function:  When you get(): when you want to get information, like requesting the price of a particular product or obtaining a list of most popular products.  When use post(): when sending data that will change information on the server, like a request to delete a file, update a database, or 80 insert new information into a database. 1/6/2012
  • 81. What is Ajax? (cont.)  Query String:  Notes: have to escape and encode query string, like:  Object Literal:  jQuery Serialize function(): collects all of the field names and the values currently in each field and creates a single query string.  Processing data from Server:  Handling Error: 81 1/6/2012
  • 82. What is Ajax? (cont.) data could be plain text, HTML, XML, or JSON 82 1/6/2012
  • 83. JSON  Stands for JavaScript Object Notation  is usually better than XML;  JSON is JavaScript, it works quickly and easily in JavaScript program.  getJSON() function: 83 1/6/2012
  • 84. JSON (cont.)  Access JSON Data:  Simple data:  Complex data: 84 1/6/2012
  • 85. JSONP  b/c Ajax requests are limited to the same domain.  stands for JSON with padding. provides one way to retrieve information from another site.  Ajax request of the foreign site, you load a script that contains the JSON code in it. Or linking to an external JavaScript file on Google.  For example: 85 1/6/2012
  • 86. Tips and tricks  Useful tips:  $() Is the Same as jQuery() like  Saving selections into variables  Or use chaining:  Instead of :  Putting reference in variable: 86 1/6/2012
  • 87. Tips and tricks (cont.)  Adding contents few times as possible NOT  Use:  Optimize your selector:  Use ID selectors if at all possible.  Use IDs first, as part of a descendent selector.  Use find function: 87 1/6/2012
  • 88. Tips and tricks (cont.)  Using the jQuery docs efficiently: http://docs.jquery.com/ (especially the jQuery API)  Compress your JavaScript and other file before deploy your website: http://developer.yahoo.com/yui/compressor  Use firebug – Firefox plugin debugger efficiently http://www.youtube.com/watch?v=1rfiPaWz4No  jQuery plugin site: http://plugins.jquery.com/  jQuery UI site: http://jqueryui.com 88 1/6/2012
  • 89. Conclusion  JavaScript is great, but it is also difficult for you to conquer, you should use jQuery instead!  jQuery isn’t only about simpler code and being more productive.  It is also about great community, support, tutorials, plugins, open (free) license, test coverage books, speed, light weight code  Keep the jQuery cheat sheet beside you when working with jQuery  Practice the tutorial in main reference book! 89 1/6/2012
  • 90. References  JavaScript and jQuery the missing manual, 2nd Edition 2011- David Sawyer McFarland  JavaScript 1.6 Visual Cheat Sheet Suggest Reading  jQuery in Actions by Bear Bibeault and Yehuda Katz  Head First JavaScript by Michael Morrison (O’Reilly) 90 1/6/2012
  • 91. Thanks for your watching! Editor: Nguyễn Đức Minh Khôi Email: nguyenducminhkhoi@gmail.com