SlideShare ist ein Scribd-Unternehmen logo
1 von 66
Downloaden Sie, um offline zu lesen
JavaScript: DOM / jQuery
Wei-Shao Tang
May 5, 2015
Topics Covered
How Browser Works.
DOM and DOM API.
jQuery Library.
DOM Traversal and Manipulation
Event-Driven Programming
AJAX
jQuery plugins (Bootstrap)
NOTICE: This tutorial includes interactive demo, it’s better to
see html version if you currently aren’t: http:
//pa4373.github.io/jstutorials/dom_jquery.html
How Browser Works?
Given the following html snippet:
1 <html lang='en'>
2 <head>
3 <meta charset='utf-8'>
4 <title>Sample Page</title>
5 </head>
6 <body>
7 <div id='content'></div>
8 <script type='text/javascript'>
9 (function () {
10 var domObj = document.getElementById('content');
11 domObj.innerHTML = 'Hello World!';
12 })();
13 </script>
14 </body>
15 </html>
How Browser Works? (Cont’d)
It can be transformed to what we see:
How Browser Works? (Partially)
Source → (DOM Parser) → DOM Tree → (Render Engine) →
What we saw.
1. Source code (plain text) will be parsed to DOM tree.
2. With DOM tree, browser will render content on the screen
accordingly. (with CSS, if exists.)
DOM stands for Document Object Model.
DOM Tree is essentially data represented in tree
structure.
DOM and DOM API
Such design enables the possibility to use a script language to
provide interaction with users.
After DOM objects were created, the script has access to those
objects via DOM API.
In the context, the script is written in JavaScript.
There might be others such as VBScript (dead already), Java
Applet. . .
Remark: The program responsible for executing JavaScript
codes called ‘JavaScript Engine.’
DOM API (in JavaScript)
DOM API looks like this:
1 var domObj = document.getElementById('content');
2 // get dom object which 'id' is 'content'
3 var newDomObj = document.createTextNode("Water");
4 // create new dom object.
5 domObj.appendChild(newDomObj);
6 // insert new node to the selected as its child.
7 domObj.addEventListener('click', function () {
8 window.alert('WHOOOPAH!');
9 });
10 // Upon clicking the text, show the alert box.
DOM API (in Javascript, Cont’d)
It includes:
Traversal: Select DOM objects satisfying criteria.
Manipulation: Change its attributes, add / remove it’s parent /
children node and such.
Event Handling: Binding functions when certain events occur,
such as click.
Basically, you operate on a tree structure.
More
How to write JavaScript in Browser?
Either by putting codes inline in <script> tag:
1 ...
2 <script type='text/javascript'>
3 (function () {
4 your code goes here.....
5 })();
6 </script>
7 </body>
8 </html>
or link to external file:
1 <script type='text/javascript' src='main.js'></script>
where JavaScript codes lie in main.js.
How to write JavaScript in Browser? (Cont’d)
Where to put the script tags?
Well, it varies, the main concerns are:
1. Validity of HTML
2. Synchronous Loading (Blocking)
Validity of HTML means your code following the standard of
HTML structure.
Synchronous Loading: When browser loads your HTML, it
parses line by line, constructs DOM tree and renders
accordingly.
If it encounters script tags, either it executes immediately,
or it loads external files.
All operations blocks the web page rendering.
How to write JavaScript in Browser? (Cont’d)
Few years ago, it’s wildly recommended to put script tags at
the bottom of body section, since JS codes don’t load until
DOM tree is constructed:
However, if your codebase is quite large (think of Facebook),
your users have to wait longer for your application initialised.
For small size program, this works just fine.
For modern browsers, you can put script tags at the
bottom of head with async or defer attributes:
1 <script type='text/javascript' src='app1.js' defer></script
2 <script type='text/javascript' src='app2.js' defer></script
Scripts with async tag executes immediately upon file is
loaded, which is non-deterministic, while defer tag ensures
your files executes in sequence asynchronously.
Debug trick
WARNING: The trick code demonstrated below shall be in
development only, remove it when it’s ready to go production.
1. console.log: Print text under the JavaScript REPL. If your
input is object / array, it allows you to inspect its attribute.
Figure 2: console.log on REPL
Debugger
‘The formal way’ to debug your application. (see the joke)
Basic steps:
1. Navigate to the code section you would like to inspect.
2. Set proper breakpoints
3. Execute program, and the program stops at breakpoints.
4. Inspect the program state at the moment.
Details varies in different browsers, you might want to check
out yourself:
Firefox: https:
//developer.mozilla.org/en-UK/docs/Tools/Debugger
Chrome: https://developer.chrome.com/devtools/docs/
javascript-debugging
jQuery
DOM Traversal / Manipulation can be tedious, using native
API.
You need to pay attention to Cross-Browser compatibility.
Writing DOM animation can be hard, at least for me. (though
with the advent of CSS3 animation it changes.)
jQuery (Cont’d)
To address those problems, jQuery was born to simplify those
task:
1 var domObj = document.getElementById('content');
2 domObj.innerHTML = 'Hello World!';
3 // Using Native DOM API
4 $('#content').text('Hello World!');
5 // Using jQuery
Originally written by John Resig, jQuery is the most popular
JavaScript library in use today. (source)
Massive plugins to create different effects.
While experienced programmers tend to reduce their
dependence on jQuery for better portability, modularity and
performance, it increases the development speed.
REMARK: jQuery is a library, and your vanilla JavaScript works
just fine without it. (see the prank)
How to use jQuery
We sticks to jQuery 2.x in this tutorial.
1. You need to include it in your page at first.
1.1 Navigate to https://jquery.com/download/, download the
compressed, production version.
1.2 Let’s assume the downloaded file called jquery.min.js, include
it in your page:
1 <script type='text/javascript' src='jquery.min.js'></scr
1.3 Put your script tag below the jQuery tag.
2. To test if it works, put the following code and test if jQuery
works:
1 $(document).ready(function (){
2 $('body').text('jQuery works!');
3 });
(or just puts your download link in src directly.)
Basic Model
jQuery is a giant function (object) with an identifier, usually
with $. (jQuery itself works.)
DOM:
1. You select some elements.
2. and you either manipulate them or bind events for them.
(object method)
3. (or using jQuery to create new DOM and insert to page later.)
Not-related to DOM: Simplified helper function to work with.
(function, ex: jQuery’s ajax function: $.ajax)
$(document).ready(fn)
A page can’t be manipulated safely until the document is
loaded.
We’ve seen this in Synchronous Loading.
Instead of moving around your script tag, jQuery provides a
method on document object, which binds function to event
when your page is loaded. (a.k.a ready):
1 $(document).ready(function () {
2 // your code won't run until the page is ready.
3 });
4 // your code runs as soon as loaded.
which can be simplified into:
1 $(function () {
2 // your code won't run until the page is ready.
3 });
It’s good habit to put your code in the supplied function.
DOM Traversal
In jQuery, DOM traversal can be seen as three kinds:
1. Ad-Hoc Selection: Using CSS selector to directly specify
elements in documents.
2. Relative Position Lookup: Given one node on DOM tree, find
its parent / children nodes.
3. Filtering current collections.
1 var contentNode = $('#content');
2 // Fetch the node with id `content`
3 contentNode.children().filter(':even')
4 .each(function () {
5 window.alert($(this).text());
6 });
7 /* Fetch its children, choose the even ones only,
8 and print out its value,
9 the form is tricky for now, but we'll see it later.*/
DOM Traversal (Cont’d)
CSS Selector: Pretty much the same as what you learned in
CSS3 part.
To inspect quickly: Fire up [Inspect Element], navigate to
[Inspector], look for desired dom object and right click [Get
Unique Selector] (Firefox)
the results you got, known as jQuery collection, which you
can manipulate later on.
When you applied method related to DOM traversal /
manipulation, jQuery returns itself, hence it supports chaining.
Function chaining:
Recall string example:
1 'I'm gonna be 500 Miles'
2 .replace('gonna be ', 'would walk ').toUpperCase();
3 //: "I'M WOULD WALK 500 MILES"
You can see after replace function is applied, a new string is
generated, and the new string invokes toUpperCase method
and so on..
Intuitively, The function acts as giant function (object) with
internal states change, and this case applied to jQuery, too.
REMARK: String operation is actually object wrapper.
Hence we can see jQuery collection as jQuery function with
references to selected objects.
Technical detail: You can enable chaining by return this
(current object) in your object method. See more.
DOM Traversal (Cont’d)
Consider the following HTML and JavaScript snippets, it
converts all characters to upper case:
1 <blockquote id='hawking'>
2 The victim should have the right to end his life,
3 if he wants. But I think it would be a great mistake.
4 However bad life may seem, there is always something
5 you can do, and succeed at.
6 While there's life, there is hope. ~ Stephen Hawking
7 </blockquote>
1 var hawkingQuote = $('#hawking');
2 var text = hawkingQuote.text();
3 hawkingQuote.text(text.toUpperCase());
DOM Traversal (Cont’d)
Checkout the demo:
[Hover over me to see demo.]
The victim should have the right to end his life, if he wants. But I
think it would be a great mistake. However bad life may seem, there
is always something you can do, and succeed at. While there’s life,
there is hope. ~ Stephen Hawking
DOM Traversal (Cont’d)
What happened?
1 var hawkingQuote = $('#hawking');
2 var text = hawkingQuote.html();
3 hawkingQuote.html(text.toUpperCase());
In line 1, we initialise our jQuery function with nevigating its
focus on ‘hawking’ object.
It’s ad-hoc selection, with jQuery collection containing one
object.
To extract its value, we call text function in line 2 and it
returns;
Then, we set its value with uppercased version of the string, in
line 3.
Although we haven’t covered DOM manipulation, yet. See
text as content getter / setter, depending on whether the
parameter is given.
DOM Traversal (Cont’d)
Another example. It converts to upper case if the item is
odd-indexed.
1 <ol id='songList'>
2 <li>Led Zeppelin - Kashmir</li>
3 <li>Billy Joel - Piano Man</li>
4 <li>John Mayer - Gravity</li>
5 <li>The Black Angels - Young Men Dead</li>
6 <li>John Mayer - Slow Dancing In A Burning Room</li
7 <li>Jimi Hendrix - Voodoo Chile</li>
8 </ol>
1 $('#songList').children().filter(':even')
2 .each(function (idx, ele) {
3 var newText = $(ele).text().toUpperCase();
4 $(ele).text(newText);
5 });
DOM Traversal (Cont’d)
Check out the demo:
[Hover over me to see demo.]
1. Led Zeppelin - Kashmir
2. Billy Joel - Piano Man
3. John Mayer - Gravity
4. The Black Angels - Young Men Dead
5. John Mayer - Slow Dancing In A Burning Room
6. Jimi Hendrix - Voodoo Chile
DOM Traversal (Cont’d)
What happened?
1 $('#songList').children().filter(':even')
2 .each(function (idx, ele) {
3 var newText = $(ele).text().toUpperCase();
4 $(ele).text(newText);
5 });
In line 1, we select songList item, get its children nodes, and
then convert some to upper case.
1. For $(‘#songList’), it’s standard ad-hoc selection with one
object in jQuery collection. (ol)
2. then we use children method to get its children, it’s relative
position lookup, resulted in multiple objects in collection.
(multiple li)
DOM Traversal (Cont’d)
What happened?
1 $('#songList').children().filter(':even')
2 .each(function (idx, ele) {
3 var newText = $(ele).text().toUpperCase();
4 $(ele).text(newText);
5 });
In Line 2, we choose the even elements, using filter, resulted
in the subset of the previous collection. (multiple li)
Then we ITERATE the collection, using each method.
DOM Traversal (Cont’d)
Why not for (; ;) loop?
Well, because what you got is not an array or any array-like
object.
However, it suffice to provide equivalent effect as for loop:
inx: the current index of the object, starting from 0.
ele: the current item. To use with jQuery, pass it to $ again.
Conceptual Analogy:
1 $coll.each(function (inx, ele) {
2 // code block....
3 });
4
5 for (var inx = 0; inx < $coll.length; inx = inx + 1) {
6 var ele = $coll[inx];
7 // code block....
8 }
9 // Note this won't work in real case.
DOM Traversal (Cont’d)
In contrast to children method, parents method gets the
parent node of the current node.
For complete ad-doc selection, consult: http://api.jquery.
com/category/selectors/hierarchy-selectors/
For filtering, consult: http:
//api.jquery.com/category/traversing/filtering/
For complete tree traversal, consult:
http://api.jquery.com/category/traversing/
This concludes the DOM traversal chapter.
DOM Manipulation
After you located your target collection, you can:
1. Read / Modify its CSS class and CSS style.
2. Read / Modify its attribute. (href, src . . . )
3. Insert / Remove element around them.
4. Use some built-in animations.
Based on those operations, you can even use plugins to create
astonishing effects with little effort.
DOM Manipulation (Cont’d)
Given the following HTML, CSS, and JavaScript snippets:
1 <blockquote id='russell'>
2 A man would not say "I hope the first President of the
3 United States will be the first President of the United
4 States" unless he had an unusual passion for the law of
5 identity. ~ Bertrand Russell, Western Philosophy
6 </blockquote>
1 .quote-border {
2 border: 1px #777 dashed;
3 margin: 5px;
4 }
1 $('#russell').addClass('quote-border');
DOM Manipulation (Cont’d)
See the live demo:
[Hover over me to see demo.]
A man would not say “I hope the first President of the United
States will be the first President of the United States” unless he had
an unusual passion for the law of identity. ~ Bertrand Russell,
Western Philosophy
DOM Manipulation (Cont’d)
It’s obvious that addClass will append new class to elements
class attribute.
The opposite of addClass is removeClass.
DOM Manipulation (Cont’d)
Given the following HTML and JavaScript snippets:
1 <img src='assets/hover1.jpg' id='barney'>
1 var barney = $('#barney');
2 var original = barney.attr('src');
3 // original will hold 'assets/hover1.jpg'
4 barney.attr('src', 'assets/hover2.jpg');
attr is also a setter / getter, depending on whether the
parameter is given.
in line 4, it changes its value to assets/hover2.jpg
DOM Manipulation (Cont’d)
See the demo:
[Hover over me to see demo.]
DOM Manipulation (Cont’d)
Given the following HTML, CSS and JavaScript snippets:
1 <div id='source'>
2 Come back you little bastard!
3 </div>
4 <div id='target'>
5 Mom, I'm here!
6 </div>
1 #target {
2 border: 1px #777 solid;
3 }
1 var source = $('#source')
2 $('#target').append(source);
DOM Manipulation (Cont’d)
See the live demo: [Hover over me to see demo.]
Come back you little bastard!
Mom, I’m here!
append method will inject elements (selected by $) inside the
object.
The opposite is remove.
If you want to inject a copy instead of original one, use
$('#source').clone() instead.
Some other common methods are: after, before. . . ..
DOM Manipulation (Cont’d)
Animation: Some jQuery methods encapsulating underlying
css / time operations.
fadeIn, fadeOut: elements fade in / away in the given time
interval.
show, hide: elements show / hide immediately.
DOM Manipulation (Cont’d)
Consider the following HTML, Javascript snippets:
1 <div id='fade-away'>
2 I'm gonna be gone.
3 </div>
1 $('#fade-away').fadeOut(1000, function () {
2 window.alert('BOOM!');
3 });
DOM Manipulation (Cont’d)
See the live demo:
[Hover over me to see demo.]
I’m gonna be gone.
It shows that #fade-away object will fade out in 1000
milliseconds.
It can also be slow, fast string.
After it’s completely gone, the callback will trigger, showing
one alert box.
Callback function is optional, you can disable it by simply not
giving a callback function.
DOM Manipulation (Cont’d)
For all manipulation API, consult:
http://api.jquery.com/category/manipulation/
Event-driven Programming
To make your program interact with users, your program need
to know how to respond user action.
Event: Certain action occurring upon certain elements. (ex:
click on #sampleObject)
Handler: The piece codes executed when some events are
triggered, usually represented in the form of function in
JavaScript.
You actually have seen that in previous example, while all demo
programs are triggered by hovering your mouse over certain
area.
Some rules about event-driven programming:
Bind / unbind function to elements’ event.
Event bubbling.
Avoid conflict.
Event-driven Programming (Cont’d)
Consider the following HTML, JavaScript snippets:
1 <div id='binding-target'>
2 Can't click me.
3 </div>
1 $('#binding-target').html('Can click me.')
2 .on('click', function (e) {
3 $(this).html('I was hit! not again plz!');
4 window.alert('Event Type: '+ e.type);
5 return false;
6 });
Event-driven Programming (Cont’d)
See the live demo:
[Click me to bind]
Can’t click me.
Event-driven Programming (Cont’d)
.on( events [, selector ] [, data ], handler )
on method registers function to events. (such as click,
hover. . . )
Function invoked when certain event is triggered.
Apart from browser built-in events, you can design your own
event.
In your handler function, you can supply e as event object.
The opposite of on is off
Minor: There’s another way to invoke which supplies children
selector. It works by delegating your event to those matched
selection.
API: http://api.jquery.com/on/
Event-driven Programming (Cont’d)
DOM elements usually nested inside each other, the handler of
the parent works even if you click on it’s child.
Event bubbling: After an event triggers on the deepest possible
element, it then triggers on parents in nesting order.
Sometimes it may cause problem,
For example, in this slide (web version), you go to the next by
clicking, imagine what will happened if I didn’t take precaution
(in which case of course I did, self five!) in the previous
example.
Event-driven Programming (Cont’d)
Remember e (as event object) in handler function?
It provides two methods:
stopPropagation: It stops itself from bubbling to the parent.
preventDefault: It prevent its default action from happening.
(such as form submitting.)
return false = stopPropagation + preventDefault +
return. (returning value does no good in handler function,
right?)
Event-driven Programming (Cont’d)
In time, you may develop more complicated program require
dynamically binding / unbinding.
It’s good habit to unbind old handler before new one is
attached:
1 $('#target-binding').off('click')
2 .on('click', function () {
3 ...});
To avoid conflict and strange behaviour, best keep your logic
simple. (think about, is there cleaner way to express equivalent
program logic?)
Event-driven Programming (Cont’d)
Shortcut: on('click', handler) can be expressed as
click(handler)
This applies to : change (when value of form changes),
submit (right before the form is submitted), and such..
Event-driven Programming (Cont’d)
Actually, ready is also a binding, ($(document).ready)
For all available event, consult API:
https://api.jquery.com/category/events/
HTTP Protocol
Application protocol underlying browser communication.
Request: client constructs a request to server. (along with
information.)
Response: server will send a response to client.
HTTP Protocol
* Trying 193.203.65.45...
* Connected to pinewoodpictures.com (193.203.65.45) port 80
> GET /film/spooks-the-greater-good/ HTTP/1.1
> Host: pinewoodpictures.com
> User-Agent: curl/7.42.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Mon, 04 May 2015 16:14:18 GMT
< Server: Apache
< X-Powered-By: PHP/5.4.35
< X-Pingback: http://pinewoodpictures.com/xmlrpc.php
< Link: <http://pinewoodpictures.com/?p=292>; rel=shortlink
< Connection: close
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<
HTTP Protocol
The first part is your request header, and the second is the
response.
Request Method: what kind of operation you intended to do
on server (‘GET’, ‘POST’, and etc. . . )
Status Code: The response code indicates the status of the
operation (200 for OK, 404 for not found. . . )
You can inspect the information within the browser, using
[Inspect Element] > [Network]
AJAX
AJAX stands for Asynchronous JavaScript and XML.
Instead of one specific technology, AJAX is composed of several
different technologies, and the use of XML is not a must.
Intuitively, it use JavaScript code to retrieve partial content
from server (string mostly), and do something with the
retrieved content.
Hence it frees us from constant reloading and better
desktop-alike user experience.
AJAX
Generally, the AJAX procedure in JavaScript goes like:
1. Prepare your HTTP request: specify the request url, method
(GET, POST..), request parameter and callback function.
2. After you send your request, you let your callback function to
handle the rest. (known as asynchronous programming)
3. If it got data from server, usually in the form of JSON (or
XML), the callback function is invoked.
JSON (or XML) is plain string able to be converted (deserialise,
with JSON.parse) to data structure, or the other way around
(serialise, with JSON.stringify).
JSON, JavaScript Simple Object Notation: boolean, number,
string, array, object and friends. (sounds familiar?)
You can operate on the data structure in the callback function
after that.
Serialisation / Deserialisation of JSON
1 var obj = {
2 foo: 'bar',
3 zoo: 'car'
4 };
5 var jsonString = JSON.stringify(obj);
6 jsonString;
7 //: "{"foo":"bar","zoo":"car"}"
8 typeof jsonString;
9 //: "string"
10 var obj2 = JSON.parse(jsonString);
11 obj2;
12 //: Object { foo: "bar", zoo: "car" }
$.ajax
To do AJAX in native browser API can be really tedious.
(browser compatibility mostly.)
jQuery provides $.ajax function to simplify the task.
API: http://api.jquery.com/jquery.ajax/
$.ajax
jQuery.ajax( url [, settings ] )
Note there’s no selection this time.
url: the request url.
settings is a object containing the detail of the request and
callback. Some common ones are:
method: HTTP method you would like to perform, such as
‘GET’, ‘POST’
data: the parameters sent along with the request, can be
object ({a: 0, b: 1}), parameter string (‘a=0&b=1’)
success: A function to be called if the request succeeds.
Function( Anything data, String textStatus, jqXHR
jqXHR )
success if HTTP status code in the range of 200 to 299, or 304.
error: A function to be called if the request fails
Function( Anything data, String textStatus, jqXHR
jqXHR )
$.ajax
complete: A function to call after success and error is
called.
headers: You can put customised HTTP headers here.
(usually helpful when it comes to authorisation..)
$.ajax
Example: http://api.hostip.info/get_json.php
Please use browser to open it, you shall see:
1 {"country_name":"TAIWAN",
2 "country_code":"TW",
3 "city":"Taipei",
4 "ip":"140.112.102.93"}
This can be seen as data object in the success callback
function later.
$.ajax
Considering the following HTML and JavaScript:
1 <button id='what-my-ip'>What is my IP?</button>
1 $('#what-my-ip').click(function () {
2 $.ajax('http://api.hostip.info/get_json.php', {
3 method: 'GET',
4 success: function (data) {
5 window.alert('Hello sir, you came from ' +
6 data.city + ', ' + data.country_name +
7 ', and your IP address is ' + data.ip);
8 }
9 });
10 return false;
11 });
$.ajax
See the live demo:
What is my IP?
$.ajax
$.ajax is the core low-level interface in jQuery, there are some
shortcuts available:
$.get, $.getJSON, $.post. . .
Consult API: http:
//api.jquery.com/category/ajax/shorthand-methods/
Notice in Chrome, you need to put your website on the server
or AJAX won’t work.
To debug with remote API, some tools comes handy:
Postman - REST Client: a tool on Google Chrome to inspect
RESTful API.
RESTClient, a debugger for RESTful web services.: Firefox
people’s Postman.
curl: hardcore unix programmer use it. (not me.)
jQuery Plugins (Bootstrap)
jQuery plugins extends jQuery’s functionality to allow you do
much with little effort.
It’s impossible to cover all kind use of plugins, so the really
important thing is to know how to read plugins manual instead.
Some recommended tips:
1. Read Get started, Quick start to get the plugin run first.
2. If you can’t directly dump in API doc, see if some tutorial
available.
3. Read API doc carefully to know how to use.
For some non-trivial plugin, it usually involves some mental
model to understand. Get it first and you will learn how to use
it more efficiently.
Here, we takes Bootstrap jQuery plugins for example:
http://getbootstrap.com/javascript/

Weitere ähnliche Inhalte

Was ist angesagt?

Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
ch samaram
 

Was ist angesagt? (20)

JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Modern Web Technologies
Modern Web TechnologiesModern Web Technologies
Modern Web Technologies
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programming
 
Java scripts
Java scriptsJava scripts
Java scripts
 
Java script Session No 1
Java script Session No 1Java script Session No 1
Java script Session No 1
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Introduction to java script
Introduction to java scriptIntroduction to java script
Introduction to java script
 
Developing large scale JavaScript applications
Developing large scale JavaScript applicationsDeveloping large scale JavaScript applications
Developing large scale JavaScript applications
 
JavaScript Jump Start 20220214
JavaScript Jump Start 20220214JavaScript Jump Start 20220214
JavaScript Jump Start 20220214
 
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
React 소개 및 구현방법 Demo
React 소개 및 구현방법 DemoReact 소개 및 구현방법 Demo
React 소개 및 구현방법 Demo
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Introduction to java_script
Introduction to java_scriptIntroduction to java_script
Introduction to java_script
 
Building a Startup Stack with AngularJS
Building a Startup Stack with AngularJSBuilding a Startup Stack with AngularJS
Building a Startup Stack with AngularJS
 
Java script
Java scriptJava script
Java script
 
Front End Development: The Important Parts
Front End Development: The Important PartsFront End Development: The Important Parts
Front End Development: The Important Parts
 

Ähnlich wie JavaScript: DOM and jQuery

Ähnlich wie JavaScript: DOM and jQuery (20)

jQuery
jQueryjQuery
jQuery
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]Full Stack React Workshop [CSSC x GDSC]
Full Stack React Workshop [CSSC x GDSC]
 
jQuery and_drupal
jQuery and_drupaljQuery and_drupal
jQuery and_drupal
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
J Query
J QueryJ Query
J Query
 
jQuery basics
jQuery basicsjQuery basics
jQuery basics
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
ME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS FundamentalsME vs WEB - AngularJS Fundamentals
ME vs WEB - AngularJS Fundamentals
 
Wt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technologyWt unit 2 ppts client sied technology
Wt unit 2 ppts client sied technology
 
Wt unit 2 ppts client side technology
Wt unit 2 ppts client side technologyWt unit 2 ppts client side technology
Wt unit 2 ppts client side technology
 
27 - Panorama Necto 14 component mode & java script - visualization & data di...
27 - Panorama Necto 14 component mode & java script - visualization & data di...27 - Panorama Necto 14 component mode & java script - visualization & data di...
27 - Panorama Necto 14 component mode & java script - visualization & data di...
 
Fewd week4 slides
Fewd week4 slidesFewd week4 slides
Fewd week4 slides
 
JS basics
JS basicsJS basics
JS basics
 
Necto 16 training 20 component mode &amp; java script
Necto 16 training 20   component mode &amp; java scriptNecto 16 training 20   component mode &amp; java script
Necto 16 training 20 component mode &amp; java script
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Jquery tutorial-beginners
Jquery tutorial-beginnersJquery tutorial-beginners
Jquery tutorial-beginners
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

JavaScript: DOM and jQuery

  • 1. JavaScript: DOM / jQuery Wei-Shao Tang May 5, 2015
  • 2.
  • 3. Topics Covered How Browser Works. DOM and DOM API. jQuery Library. DOM Traversal and Manipulation Event-Driven Programming AJAX jQuery plugins (Bootstrap) NOTICE: This tutorial includes interactive demo, it’s better to see html version if you currently aren’t: http: //pa4373.github.io/jstutorials/dom_jquery.html
  • 4. How Browser Works? Given the following html snippet: 1 <html lang='en'> 2 <head> 3 <meta charset='utf-8'> 4 <title>Sample Page</title> 5 </head> 6 <body> 7 <div id='content'></div> 8 <script type='text/javascript'> 9 (function () { 10 var domObj = document.getElementById('content'); 11 domObj.innerHTML = 'Hello World!'; 12 })(); 13 </script> 14 </body> 15 </html>
  • 5. How Browser Works? (Cont’d) It can be transformed to what we see:
  • 6. How Browser Works? (Partially) Source → (DOM Parser) → DOM Tree → (Render Engine) → What we saw. 1. Source code (plain text) will be parsed to DOM tree. 2. With DOM tree, browser will render content on the screen accordingly. (with CSS, if exists.) DOM stands for Document Object Model. DOM Tree is essentially data represented in tree structure.
  • 7. DOM and DOM API Such design enables the possibility to use a script language to provide interaction with users. After DOM objects were created, the script has access to those objects via DOM API. In the context, the script is written in JavaScript. There might be others such as VBScript (dead already), Java Applet. . . Remark: The program responsible for executing JavaScript codes called ‘JavaScript Engine.’
  • 8. DOM API (in JavaScript) DOM API looks like this: 1 var domObj = document.getElementById('content'); 2 // get dom object which 'id' is 'content' 3 var newDomObj = document.createTextNode("Water"); 4 // create new dom object. 5 domObj.appendChild(newDomObj); 6 // insert new node to the selected as its child. 7 domObj.addEventListener('click', function () { 8 window.alert('WHOOOPAH!'); 9 }); 10 // Upon clicking the text, show the alert box.
  • 9. DOM API (in Javascript, Cont’d) It includes: Traversal: Select DOM objects satisfying criteria. Manipulation: Change its attributes, add / remove it’s parent / children node and such. Event Handling: Binding functions when certain events occur, such as click. Basically, you operate on a tree structure. More
  • 10. How to write JavaScript in Browser? Either by putting codes inline in <script> tag: 1 ... 2 <script type='text/javascript'> 3 (function () { 4 your code goes here..... 5 })(); 6 </script> 7 </body> 8 </html> or link to external file: 1 <script type='text/javascript' src='main.js'></script> where JavaScript codes lie in main.js.
  • 11. How to write JavaScript in Browser? (Cont’d) Where to put the script tags? Well, it varies, the main concerns are: 1. Validity of HTML 2. Synchronous Loading (Blocking) Validity of HTML means your code following the standard of HTML structure. Synchronous Loading: When browser loads your HTML, it parses line by line, constructs DOM tree and renders accordingly. If it encounters script tags, either it executes immediately, or it loads external files. All operations blocks the web page rendering.
  • 12. How to write JavaScript in Browser? (Cont’d) Few years ago, it’s wildly recommended to put script tags at the bottom of body section, since JS codes don’t load until DOM tree is constructed: However, if your codebase is quite large (think of Facebook), your users have to wait longer for your application initialised. For small size program, this works just fine. For modern browsers, you can put script tags at the bottom of head with async or defer attributes: 1 <script type='text/javascript' src='app1.js' defer></script 2 <script type='text/javascript' src='app2.js' defer></script Scripts with async tag executes immediately upon file is loaded, which is non-deterministic, while defer tag ensures your files executes in sequence asynchronously.
  • 13. Debug trick WARNING: The trick code demonstrated below shall be in development only, remove it when it’s ready to go production. 1. console.log: Print text under the JavaScript REPL. If your input is object / array, it allows you to inspect its attribute. Figure 2: console.log on REPL
  • 14. Debugger ‘The formal way’ to debug your application. (see the joke) Basic steps: 1. Navigate to the code section you would like to inspect. 2. Set proper breakpoints 3. Execute program, and the program stops at breakpoints. 4. Inspect the program state at the moment. Details varies in different browsers, you might want to check out yourself: Firefox: https: //developer.mozilla.org/en-UK/docs/Tools/Debugger Chrome: https://developer.chrome.com/devtools/docs/ javascript-debugging
  • 15. jQuery DOM Traversal / Manipulation can be tedious, using native API. You need to pay attention to Cross-Browser compatibility. Writing DOM animation can be hard, at least for me. (though with the advent of CSS3 animation it changes.)
  • 16. jQuery (Cont’d) To address those problems, jQuery was born to simplify those task: 1 var domObj = document.getElementById('content'); 2 domObj.innerHTML = 'Hello World!'; 3 // Using Native DOM API 4 $('#content').text('Hello World!'); 5 // Using jQuery Originally written by John Resig, jQuery is the most popular JavaScript library in use today. (source) Massive plugins to create different effects. While experienced programmers tend to reduce their dependence on jQuery for better portability, modularity and performance, it increases the development speed. REMARK: jQuery is a library, and your vanilla JavaScript works just fine without it. (see the prank)
  • 17. How to use jQuery We sticks to jQuery 2.x in this tutorial. 1. You need to include it in your page at first. 1.1 Navigate to https://jquery.com/download/, download the compressed, production version. 1.2 Let’s assume the downloaded file called jquery.min.js, include it in your page: 1 <script type='text/javascript' src='jquery.min.js'></scr 1.3 Put your script tag below the jQuery tag. 2. To test if it works, put the following code and test if jQuery works: 1 $(document).ready(function (){ 2 $('body').text('jQuery works!'); 3 }); (or just puts your download link in src directly.)
  • 18. Basic Model jQuery is a giant function (object) with an identifier, usually with $. (jQuery itself works.) DOM: 1. You select some elements. 2. and you either manipulate them or bind events for them. (object method) 3. (or using jQuery to create new DOM and insert to page later.) Not-related to DOM: Simplified helper function to work with. (function, ex: jQuery’s ajax function: $.ajax)
  • 19. $(document).ready(fn) A page can’t be manipulated safely until the document is loaded. We’ve seen this in Synchronous Loading. Instead of moving around your script tag, jQuery provides a method on document object, which binds function to event when your page is loaded. (a.k.a ready): 1 $(document).ready(function () { 2 // your code won't run until the page is ready. 3 }); 4 // your code runs as soon as loaded. which can be simplified into: 1 $(function () { 2 // your code won't run until the page is ready. 3 }); It’s good habit to put your code in the supplied function.
  • 20. DOM Traversal In jQuery, DOM traversal can be seen as three kinds: 1. Ad-Hoc Selection: Using CSS selector to directly specify elements in documents. 2. Relative Position Lookup: Given one node on DOM tree, find its parent / children nodes. 3. Filtering current collections. 1 var contentNode = $('#content'); 2 // Fetch the node with id `content` 3 contentNode.children().filter(':even') 4 .each(function () { 5 window.alert($(this).text()); 6 }); 7 /* Fetch its children, choose the even ones only, 8 and print out its value, 9 the form is tricky for now, but we'll see it later.*/
  • 21. DOM Traversal (Cont’d) CSS Selector: Pretty much the same as what you learned in CSS3 part. To inspect quickly: Fire up [Inspect Element], navigate to [Inspector], look for desired dom object and right click [Get Unique Selector] (Firefox) the results you got, known as jQuery collection, which you can manipulate later on. When you applied method related to DOM traversal / manipulation, jQuery returns itself, hence it supports chaining.
  • 22. Function chaining: Recall string example: 1 'I'm gonna be 500 Miles' 2 .replace('gonna be ', 'would walk ').toUpperCase(); 3 //: "I'M WOULD WALK 500 MILES" You can see after replace function is applied, a new string is generated, and the new string invokes toUpperCase method and so on.. Intuitively, The function acts as giant function (object) with internal states change, and this case applied to jQuery, too. REMARK: String operation is actually object wrapper. Hence we can see jQuery collection as jQuery function with references to selected objects. Technical detail: You can enable chaining by return this (current object) in your object method. See more.
  • 23. DOM Traversal (Cont’d) Consider the following HTML and JavaScript snippets, it converts all characters to upper case: 1 <blockquote id='hawking'> 2 The victim should have the right to end his life, 3 if he wants. But I think it would be a great mistake. 4 However bad life may seem, there is always something 5 you can do, and succeed at. 6 While there's life, there is hope. ~ Stephen Hawking 7 </blockquote> 1 var hawkingQuote = $('#hawking'); 2 var text = hawkingQuote.text(); 3 hawkingQuote.text(text.toUpperCase());
  • 24. DOM Traversal (Cont’d) Checkout the demo: [Hover over me to see demo.] The victim should have the right to end his life, if he wants. But I think it would be a great mistake. However bad life may seem, there is always something you can do, and succeed at. While there’s life, there is hope. ~ Stephen Hawking
  • 25. DOM Traversal (Cont’d) What happened? 1 var hawkingQuote = $('#hawking'); 2 var text = hawkingQuote.html(); 3 hawkingQuote.html(text.toUpperCase()); In line 1, we initialise our jQuery function with nevigating its focus on ‘hawking’ object. It’s ad-hoc selection, with jQuery collection containing one object. To extract its value, we call text function in line 2 and it returns; Then, we set its value with uppercased version of the string, in line 3. Although we haven’t covered DOM manipulation, yet. See text as content getter / setter, depending on whether the parameter is given.
  • 26. DOM Traversal (Cont’d) Another example. It converts to upper case if the item is odd-indexed. 1 <ol id='songList'> 2 <li>Led Zeppelin - Kashmir</li> 3 <li>Billy Joel - Piano Man</li> 4 <li>John Mayer - Gravity</li> 5 <li>The Black Angels - Young Men Dead</li> 6 <li>John Mayer - Slow Dancing In A Burning Room</li 7 <li>Jimi Hendrix - Voodoo Chile</li> 8 </ol> 1 $('#songList').children().filter(':even') 2 .each(function (idx, ele) { 3 var newText = $(ele).text().toUpperCase(); 4 $(ele).text(newText); 5 });
  • 27. DOM Traversal (Cont’d) Check out the demo: [Hover over me to see demo.] 1. Led Zeppelin - Kashmir 2. Billy Joel - Piano Man 3. John Mayer - Gravity 4. The Black Angels - Young Men Dead 5. John Mayer - Slow Dancing In A Burning Room 6. Jimi Hendrix - Voodoo Chile
  • 28. DOM Traversal (Cont’d) What happened? 1 $('#songList').children().filter(':even') 2 .each(function (idx, ele) { 3 var newText = $(ele).text().toUpperCase(); 4 $(ele).text(newText); 5 }); In line 1, we select songList item, get its children nodes, and then convert some to upper case. 1. For $(‘#songList’), it’s standard ad-hoc selection with one object in jQuery collection. (ol) 2. then we use children method to get its children, it’s relative position lookup, resulted in multiple objects in collection. (multiple li)
  • 29. DOM Traversal (Cont’d) What happened? 1 $('#songList').children().filter(':even') 2 .each(function (idx, ele) { 3 var newText = $(ele).text().toUpperCase(); 4 $(ele).text(newText); 5 }); In Line 2, we choose the even elements, using filter, resulted in the subset of the previous collection. (multiple li) Then we ITERATE the collection, using each method.
  • 30. DOM Traversal (Cont’d) Why not for (; ;) loop? Well, because what you got is not an array or any array-like object. However, it suffice to provide equivalent effect as for loop: inx: the current index of the object, starting from 0. ele: the current item. To use with jQuery, pass it to $ again. Conceptual Analogy: 1 $coll.each(function (inx, ele) { 2 // code block.... 3 }); 4 5 for (var inx = 0; inx < $coll.length; inx = inx + 1) { 6 var ele = $coll[inx]; 7 // code block.... 8 } 9 // Note this won't work in real case.
  • 31. DOM Traversal (Cont’d) In contrast to children method, parents method gets the parent node of the current node. For complete ad-doc selection, consult: http://api.jquery. com/category/selectors/hierarchy-selectors/ For filtering, consult: http: //api.jquery.com/category/traversing/filtering/ For complete tree traversal, consult: http://api.jquery.com/category/traversing/ This concludes the DOM traversal chapter.
  • 32. DOM Manipulation After you located your target collection, you can: 1. Read / Modify its CSS class and CSS style. 2. Read / Modify its attribute. (href, src . . . ) 3. Insert / Remove element around them. 4. Use some built-in animations. Based on those operations, you can even use plugins to create astonishing effects with little effort.
  • 33. DOM Manipulation (Cont’d) Given the following HTML, CSS, and JavaScript snippets: 1 <blockquote id='russell'> 2 A man would not say "I hope the first President of the 3 United States will be the first President of the United 4 States" unless he had an unusual passion for the law of 5 identity. ~ Bertrand Russell, Western Philosophy 6 </blockquote> 1 .quote-border { 2 border: 1px #777 dashed; 3 margin: 5px; 4 } 1 $('#russell').addClass('quote-border');
  • 34. DOM Manipulation (Cont’d) See the live demo: [Hover over me to see demo.] A man would not say “I hope the first President of the United States will be the first President of the United States” unless he had an unusual passion for the law of identity. ~ Bertrand Russell, Western Philosophy
  • 35. DOM Manipulation (Cont’d) It’s obvious that addClass will append new class to elements class attribute. The opposite of addClass is removeClass.
  • 36. DOM Manipulation (Cont’d) Given the following HTML and JavaScript snippets: 1 <img src='assets/hover1.jpg' id='barney'> 1 var barney = $('#barney'); 2 var original = barney.attr('src'); 3 // original will hold 'assets/hover1.jpg' 4 barney.attr('src', 'assets/hover2.jpg'); attr is also a setter / getter, depending on whether the parameter is given. in line 4, it changes its value to assets/hover2.jpg
  • 37. DOM Manipulation (Cont’d) See the demo: [Hover over me to see demo.]
  • 38. DOM Manipulation (Cont’d) Given the following HTML, CSS and JavaScript snippets: 1 <div id='source'> 2 Come back you little bastard! 3 </div> 4 <div id='target'> 5 Mom, I'm here! 6 </div> 1 #target { 2 border: 1px #777 solid; 3 } 1 var source = $('#source') 2 $('#target').append(source);
  • 39. DOM Manipulation (Cont’d) See the live demo: [Hover over me to see demo.] Come back you little bastard! Mom, I’m here! append method will inject elements (selected by $) inside the object. The opposite is remove. If you want to inject a copy instead of original one, use $('#source').clone() instead. Some other common methods are: after, before. . . ..
  • 40. DOM Manipulation (Cont’d) Animation: Some jQuery methods encapsulating underlying css / time operations. fadeIn, fadeOut: elements fade in / away in the given time interval. show, hide: elements show / hide immediately.
  • 41. DOM Manipulation (Cont’d) Consider the following HTML, Javascript snippets: 1 <div id='fade-away'> 2 I'm gonna be gone. 3 </div> 1 $('#fade-away').fadeOut(1000, function () { 2 window.alert('BOOM!'); 3 });
  • 42. DOM Manipulation (Cont’d) See the live demo: [Hover over me to see demo.] I’m gonna be gone. It shows that #fade-away object will fade out in 1000 milliseconds. It can also be slow, fast string. After it’s completely gone, the callback will trigger, showing one alert box. Callback function is optional, you can disable it by simply not giving a callback function.
  • 43. DOM Manipulation (Cont’d) For all manipulation API, consult: http://api.jquery.com/category/manipulation/
  • 44. Event-driven Programming To make your program interact with users, your program need to know how to respond user action. Event: Certain action occurring upon certain elements. (ex: click on #sampleObject) Handler: The piece codes executed when some events are triggered, usually represented in the form of function in JavaScript. You actually have seen that in previous example, while all demo programs are triggered by hovering your mouse over certain area. Some rules about event-driven programming: Bind / unbind function to elements’ event. Event bubbling. Avoid conflict.
  • 45. Event-driven Programming (Cont’d) Consider the following HTML, JavaScript snippets: 1 <div id='binding-target'> 2 Can't click me. 3 </div> 1 $('#binding-target').html('Can click me.') 2 .on('click', function (e) { 3 $(this).html('I was hit! not again plz!'); 4 window.alert('Event Type: '+ e.type); 5 return false; 6 });
  • 46. Event-driven Programming (Cont’d) See the live demo: [Click me to bind] Can’t click me.
  • 47. Event-driven Programming (Cont’d) .on( events [, selector ] [, data ], handler ) on method registers function to events. (such as click, hover. . . ) Function invoked when certain event is triggered. Apart from browser built-in events, you can design your own event. In your handler function, you can supply e as event object. The opposite of on is off Minor: There’s another way to invoke which supplies children selector. It works by delegating your event to those matched selection. API: http://api.jquery.com/on/
  • 48. Event-driven Programming (Cont’d) DOM elements usually nested inside each other, the handler of the parent works even if you click on it’s child. Event bubbling: After an event triggers on the deepest possible element, it then triggers on parents in nesting order. Sometimes it may cause problem, For example, in this slide (web version), you go to the next by clicking, imagine what will happened if I didn’t take precaution (in which case of course I did, self five!) in the previous example.
  • 49. Event-driven Programming (Cont’d) Remember e (as event object) in handler function? It provides two methods: stopPropagation: It stops itself from bubbling to the parent. preventDefault: It prevent its default action from happening. (such as form submitting.) return false = stopPropagation + preventDefault + return. (returning value does no good in handler function, right?)
  • 50. Event-driven Programming (Cont’d) In time, you may develop more complicated program require dynamically binding / unbinding. It’s good habit to unbind old handler before new one is attached: 1 $('#target-binding').off('click') 2 .on('click', function () { 3 ...}); To avoid conflict and strange behaviour, best keep your logic simple. (think about, is there cleaner way to express equivalent program logic?)
  • 51. Event-driven Programming (Cont’d) Shortcut: on('click', handler) can be expressed as click(handler) This applies to : change (when value of form changes), submit (right before the form is submitted), and such..
  • 52. Event-driven Programming (Cont’d) Actually, ready is also a binding, ($(document).ready) For all available event, consult API: https://api.jquery.com/category/events/
  • 53. HTTP Protocol Application protocol underlying browser communication. Request: client constructs a request to server. (along with information.) Response: server will send a response to client.
  • 54. HTTP Protocol * Trying 193.203.65.45... * Connected to pinewoodpictures.com (193.203.65.45) port 80 > GET /film/spooks-the-greater-good/ HTTP/1.1 > Host: pinewoodpictures.com > User-Agent: curl/7.42.0 > Accept: */* > < HTTP/1.1 200 OK < Date: Mon, 04 May 2015 16:14:18 GMT < Server: Apache < X-Powered-By: PHP/5.4.35 < X-Pingback: http://pinewoodpictures.com/xmlrpc.php < Link: <http://pinewoodpictures.com/?p=292>; rel=shortlink < Connection: close < Transfer-Encoding: chunked < Content-Type: text/html; charset=UTF-8 <
  • 55. HTTP Protocol The first part is your request header, and the second is the response. Request Method: what kind of operation you intended to do on server (‘GET’, ‘POST’, and etc. . . ) Status Code: The response code indicates the status of the operation (200 for OK, 404 for not found. . . ) You can inspect the information within the browser, using [Inspect Element] > [Network]
  • 56. AJAX AJAX stands for Asynchronous JavaScript and XML. Instead of one specific technology, AJAX is composed of several different technologies, and the use of XML is not a must. Intuitively, it use JavaScript code to retrieve partial content from server (string mostly), and do something with the retrieved content. Hence it frees us from constant reloading and better desktop-alike user experience.
  • 57. AJAX Generally, the AJAX procedure in JavaScript goes like: 1. Prepare your HTTP request: specify the request url, method (GET, POST..), request parameter and callback function. 2. After you send your request, you let your callback function to handle the rest. (known as asynchronous programming) 3. If it got data from server, usually in the form of JSON (or XML), the callback function is invoked. JSON (or XML) is plain string able to be converted (deserialise, with JSON.parse) to data structure, or the other way around (serialise, with JSON.stringify). JSON, JavaScript Simple Object Notation: boolean, number, string, array, object and friends. (sounds familiar?) You can operate on the data structure in the callback function after that.
  • 58. Serialisation / Deserialisation of JSON 1 var obj = { 2 foo: 'bar', 3 zoo: 'car' 4 }; 5 var jsonString = JSON.stringify(obj); 6 jsonString; 7 //: "{"foo":"bar","zoo":"car"}" 8 typeof jsonString; 9 //: "string" 10 var obj2 = JSON.parse(jsonString); 11 obj2; 12 //: Object { foo: "bar", zoo: "car" }
  • 59. $.ajax To do AJAX in native browser API can be really tedious. (browser compatibility mostly.) jQuery provides $.ajax function to simplify the task. API: http://api.jquery.com/jquery.ajax/
  • 60. $.ajax jQuery.ajax( url [, settings ] ) Note there’s no selection this time. url: the request url. settings is a object containing the detail of the request and callback. Some common ones are: method: HTTP method you would like to perform, such as ‘GET’, ‘POST’ data: the parameters sent along with the request, can be object ({a: 0, b: 1}), parameter string (‘a=0&b=1’) success: A function to be called if the request succeeds. Function( Anything data, String textStatus, jqXHR jqXHR ) success if HTTP status code in the range of 200 to 299, or 304. error: A function to be called if the request fails Function( Anything data, String textStatus, jqXHR jqXHR )
  • 61. $.ajax complete: A function to call after success and error is called. headers: You can put customised HTTP headers here. (usually helpful when it comes to authorisation..)
  • 62. $.ajax Example: http://api.hostip.info/get_json.php Please use browser to open it, you shall see: 1 {"country_name":"TAIWAN", 2 "country_code":"TW", 3 "city":"Taipei", 4 "ip":"140.112.102.93"} This can be seen as data object in the success callback function later.
  • 63. $.ajax Considering the following HTML and JavaScript: 1 <button id='what-my-ip'>What is my IP?</button> 1 $('#what-my-ip').click(function () { 2 $.ajax('http://api.hostip.info/get_json.php', { 3 method: 'GET', 4 success: function (data) { 5 window.alert('Hello sir, you came from ' + 6 data.city + ', ' + data.country_name + 7 ', and your IP address is ' + data.ip); 8 } 9 }); 10 return false; 11 });
  • 64. $.ajax See the live demo: What is my IP?
  • 65. $.ajax $.ajax is the core low-level interface in jQuery, there are some shortcuts available: $.get, $.getJSON, $.post. . . Consult API: http: //api.jquery.com/category/ajax/shorthand-methods/ Notice in Chrome, you need to put your website on the server or AJAX won’t work. To debug with remote API, some tools comes handy: Postman - REST Client: a tool on Google Chrome to inspect RESTful API. RESTClient, a debugger for RESTful web services.: Firefox people’s Postman. curl: hardcore unix programmer use it. (not me.)
  • 66. jQuery Plugins (Bootstrap) jQuery plugins extends jQuery’s functionality to allow you do much with little effort. It’s impossible to cover all kind use of plugins, so the really important thing is to know how to read plugins manual instead. Some recommended tips: 1. Read Get started, Quick start to get the plugin run first. 2. If you can’t directly dump in API doc, see if some tutorial available. 3. Read API doc carefully to know how to use. For some non-trivial plugin, it usually involves some mental model to understand. Get it first and you will learn how to use it more efficiently. Here, we takes Bootstrap jQuery plugins for example: http://getbootstrap.com/javascript/