... … by Martin Kruliš (v1.2)"> ... … by Martin Kruliš (v1.2)">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript UI Development and jQuery Library

Similar presentations


Presentation on theme: "JavaScript UI Development and jQuery Library"— Presentation transcript:

1 JavaScript UI Development and jQuery Library
Martin Kruliš by Martin Kruliš (v1.2)

2 Document Object Model …
Revision body h1 p img Document src DOM Example Document Object Model … alt html Document Object Model <html> <body> <h1>DOM Example</h1> <p> Document Object Model is an API … </p> <img src="url" alt="text"> ... </body> </html> by Martin Kruliš (v1.2)

3 Revision DOM Node Traversing Node.firstChild, Node.lastChild
Node.childNodes Node.nextSibling, Node.previousSibling Node.parentNode, Node.parentElement Node.nodeName, Node.nodeValue Node.attributes – relevant for elements only Document.documentElement – root element Document.getElementsByTagName(tagName) Document.getElementById(id) by Martin Kruliš (v1.2)

4 Revision DOM Content Manipulation Extra Features
Document.createElement(), … Node.appendChild(), Node.insertBefore() Node.replaceChild(), Node.removeChild() Element.getAttribute(), Element.setAttribute() Element.removeAttribute() Node.cloneNode(deep) Extra Features Node.innerHTML, Node.outerHTML Document.evaluate(xpath) by Martin Kruliš (v1.2)

5 Revision Event Model Top-level scripts are executed immediately
Other code can be attached to various events One event loop processed in single thread If the event is not processed, it bubbles up DOM Tree Processes one event at a time Mouse Moved User Clicked Event Queue Dispatcher Loading Finished Target Window Resized Target element is found … by Martin Kruliš (v1.2)

6 Revision Event Handling Events may be handled by callback functions
Attached directly in HTML <button onclick="js code handling the event"> Or by Javascript code myButton.onclick = function(event) { ... } or myButton.addEventListener('click', fnc, capture); Todays choice – addEventListener() Allows multiple handlers on one event Works on any DOM element (not just HTML) Allows early event capturing First example is presented in JSFiddle environment on webik.ms.mff.cuni.cz. Example 1 by Martin Kruliš (v1.2)

7 DOM DOM Issues DOM is generic API Writing DOM code is rather tedious
It aims to cover functionality, not to streamline code It is also being steered by other languages (e.g. XML) Writing DOM code is rather tedious Considering most task have repetitive pattern (e.g., binding event handlers) Compatibility issues in mainstream browsers DOM1 is supported, DOM2 mostly, and DOM3 partially by Martin Kruliš (v1.2)

8 jQuery jQuery Library Modern JavaScript library for basic operations
Easy to learn and use Lightweight footprint Supports almost all currently used browsers Key features Simplified DOM traversal and manipulation Event handling CSS based animations and effects Unified AJAX API with support for data (de)serialization Extendable with plugins and UI libraries by Martin Kruliš (v1.2)

9 jQuery Object jQuery Object “Select and Do” Philosophy
Function object in global name jQuery and $ Acts as a function that returns set of nodes and as a container object for library functions “Select and Do” Philosophy Select a set of DOM nodes Apply (a sequence of) operation(s) on the whole set of selected nodes Most methods support invocation chaining $(selector).doIt().doAnother().doSometingElse(); by Martin Kruliš (v1.2)

10 Selectors Selector Selects set of DOM nodes for further usage
$("selector") or $(DOMnode) or $("HTMLfragment") jQuery Selectors are inspired by CSS3 selectors "div" – select elements of given name "#id" – select element by its ID ".class" – select elements with specific CSS class "ancestor descendant" – express DOM relations :disabled, :visible, :checked, … Subsequent operations work on the whole set $(".secret").hide(); by Martin Kruliš (v1.2)

11 DOM Manipulation Manipulating HTML Structure
Wrappers for DOM manipulation functions prepend(), append(), before(), after() – insert content before/after inside/outside selected elements remove(), empty(), detach() – remove (child) nodes replaceAll(), replaceWith() html(), text() – manipulate with content clone() – create a deep copy of the element attr(), prop(), removeAttr(), removeProp() Attr ~ HTML attributes, prop ~ properties (checked, …) Reading methods take only the first element in set by Martin Kruliš (v1.2)

12 DOM Traversal Traversing DOM Tree Similar to XPath processing
Using set of nodes as starting point add() – unite one set with another children() – get children of all nodes next() – get next sibling for each node parents() – get all node ancestors Node set filtering filter() – filter by functor or selector not() – remove given nodes (or by selector) slice() – get a subrange (by indices) The selected functions are only illustrative. There are many more of them. by Martin Kruliš (v1.2)

13 Events Event Handlers Binding Bind handlers by event name
on(), off(), one() jQuery.proxy() – binds functor within a context Triggering events - trigger(), triggerHandler() Document loading events $(document).load(), .unload(), .ready() Specialized event handling/triggering functions click(), mousedown(), hover(), keydown(), … Event object is wrapped in jQuery.Event $(document).ready(handler) is special event that is triggered when all document contents (images, scripts, …) is loaded. It has also two shorthand notations $().ready(handler) and $(handler). by Martin Kruliš (v1.2)

14 CSS Cascading Style Sheets Manipulation Reading writing all properties
css(property [, value]) Manipulation with CSS classes addClass(), removeClass(), hasClass(), toggleClass() Element position position(), offset() Element size height(), width(), innerHeight(), outerWidth() The CSS management mechanism can be overridden for specific properties by jQuery.cssHooks() by Martin Kruliš (v1.2)

15 Effects Animations Achieved using CSS properties and timers
Each element have its own effect queue Animations are inserted in the queue and processed iteratively by timer handler queue(), dequeue(), clearQueue(), stop(), finish(), delay() animate() – inserting custom CSS animations With specified duration and interpolation function hide(), show(), toggle() fadeIn(), fadeOut(), slideDown(), slideUp() Note that some (actually most) of these animations can be performed by CSS3 transitions and animations. However, jQuery was designed before CSS3 become widely implemented, thus it may provide help in situations, when old browsers has to be supported. by Martin Kruliš (v1.2)

16 AJAX Wrapper for Asynchronous Transfers jQuery.ajax() – create request
Allows many parameters to be set easily Handlers can be attached to created request object ajaxComplete(), ajaxError(), ajaxSend(), … Helper functions for data (de)serialization serialize(), serializeArray(), jQuery.param() Shorthand functions for usual use cases get(), getJSON(), getScript(), post(), load() by Martin Kruliš (v1.2)

17 Deferred Objects Asynchronous Events
Problem with chaining handlers of async. operations jQuery.Deferred object represents pending action The action can end successfully or fail resolve(), resolveWith(), fail(), failWith() Handlers can be attached to various events done(), fail(), always(), then() Operation progress can be reported (if applicable) notify(), notifyWith(), progress() promise() – returns promise object Restricted API that do not allow object modification Deferred object aggregation jQuery.when() The deferred object becomes obsolete in Ecmascript 6, as it can be replaced with Promise object. by Martin Kruliš (v1.2)

18 Callback Objects Managing Callback Queues
If you create complex APIs, your objects may need to report events as well jQuery.Callbacks() – returns callback list object Basic functions for callback manipulation add(), remove(), has() Fire the event and call all callbacks fire(), fireWith() And provide some additional control disable(), lock() Note that callbacks are called synchronously Be careful when firing callbacks inside callbacks by Martin Kruliš (v1.2)

19 Some Useful Techniques
CSS Classes as Flags CSS class assigned to an element is typically used to alter appearance It may also be used as a state indicator $(".selectable").click(function(){ $(this).toggleClass("selected"); }); $("#saveBtn").click(function(){ var items = []; $(".selected").each(function(){ items.push($(this).attr("id")); ... }); by Martin Kruliš (v1.2)

20 Some Useful Techniques
Content Hiding The entire content of the web (page) is loaded Currently irrelevant parts are hidden by a script Used in various UI patterns Page tabs, Accordion, Expanding tree, Form wizard, … Content Replication Repetitive parts of HTML structure Data table rows, multi-input forms, … Hidden HTML fragment (template) The template is cloned, inserted at a proper place, and shown Example 2 by Martin Kruliš (v1.2)

21 Some Useful Techniques
AJAX Overrides Action Buttons Simple operations that does not require input Switch state, delete, generate password, start service, … Designed as a hyperlink, but handled by JavaScript Click event initiates AJAX POST request instead AJAX Forms Submit event is overridden, form contents is assembled into POST request and sent by AJAX request Much simpler handling of user errors (invalid fields) Does not require session storage like sticky forms Example 3 by Martin Kruliš (v1.2)

22 jQuery UI jQuery User Interface Widgets
Separate library with non-standard UI components Containers Accordion, Tabs, Dialog Text input augmentations Autocomplete, Date picker, Spinner Specialized controls Progress bar, Slider, (Nested) Menu Various helpers Button, Tooltip API (abstraction) for your own widgets The examples can be found on the website. Example by Martin Kruliš (v1.2)

23 jQuery Mobile jQuery Mobile Specialize branch for handheld devices
Particular emphasis on portability HTML5-based UI, which is optimized for touch screens Integrated with modern CSS and theme support Widgets specialized for various screen sizes by Martin Kruliš (v1.2)

24 QUnit Unit Tests for JavaScript
Platform for in-browser JS code testing Used along with (and also tests) jQuery, jQuery UI, and jQuery Mobile API for test specification test( "hello test", function() { ok( 1 == "1", "Passed!" ); }); Various helper functions for creating assertions by Martin Kruliš (v1.2)

25 Discussion by Martin Kruliš (v1.2)


Download ppt "JavaScript UI Development and jQuery Library"

Similar presentations


Ads by Google