- jQuery uses CSS-style selectors to select elements and create wrapped sets that allow accessing and manipulating elements
- Objects in JavaScript can contain functions and properties, and functions are also objects that can be passed around and assigned to properties
- Event handling in jQuery provides a cross-browser way to attach multiple handlers to events and prevent default behavior
- jQuery methods like bind(), live(), delegate() allow attaching handlers to current and future elements, and events can be hijacked to make AJAX requests instead of full page posts
This document discusses advanced JavaScript techniques. It covers object-oriented JavaScript concepts like references, function overloading, type checking, scopes, closures, object creation, and inheritance. It also discusses performance improvements like scope management, object caching, and optimizing DOM selection. Finally, it discusses debugging and testing JavaScript code as well as distributing JavaScript applications.
Powerful JavaScript Tips and Best PracticesDragos Ionita
The document provides 11 powerful JavaScript tips and best practices for programmers, including using short-circuit evaluation to set default values, immediately invoked function expressions to avoid polluting the global namespace, and splice instead of delete to remove array items without leaving undefined holes.
JavaScript is a scripting language used to make web pages interactive. It was created in 1995 and standardized as ECMAScript. JavaScript can access and modify the content, structure, and style of documents. It is used to handle events, perform animations, and interact with forms on web pages. Common uses of JavaScript include form validation, navigation menus, lightboxes, and sliders on websites.
This document provides an introduction to JavaScript including:
- JavaScript is an object-oriented scripting language that is a dialect of ECMAScript.
- It was originally designed to add interactivity to HTML pages through dynamic HTML, reacting to events, and data validation.
- JavaScript is now heavily used in AJAX-based sites to asynchronously retrieve and display data without reloading pages.
- The document discusses JavaScript compatibility issues and provides examples of basic JavaScript concepts like variables, comparisons, repetition, and popup boxes.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
This document provides tips and tricks for using jQuery. It discusses selecting elements by ID or class and the differences in performance. It recommends caching frequently used objects, binding events, and manipulating the DOM in certain ways for better performance. Useful jQuery plugins are also mentioned like Tipsy for tooltips, Nivo Slider for image sliders, and Shadowbox for lightboxes. Best practices like unit testing, benchmarking, and avoiding certain DOM manipulation functions are advised.
This document discusses advanced JavaScript techniques. It covers object-oriented JavaScript concepts like references, function overloading, type checking, scopes, closures, object creation, and inheritance. It also discusses performance improvements like scope management, object caching, and optimizing DOM selection. Finally, it discusses debugging and testing JavaScript code as well as distributing JavaScript applications.
Powerful JavaScript Tips and Best PracticesDragos Ionita
The document provides 11 powerful JavaScript tips and best practices for programmers, including using short-circuit evaluation to set default values, immediately invoked function expressions to avoid polluting the global namespace, and splice instead of delete to remove array items without leaving undefined holes.
JavaScript is a scripting language used to make web pages interactive. It was created in 1995 and standardized as ECMAScript. JavaScript can access and modify the content, structure, and style of documents. It is used to handle events, perform animations, and interact with forms on web pages. Common uses of JavaScript include form validation, navigation menus, lightboxes, and sliders on websites.
This document provides an introduction to JavaScript including:
- JavaScript is an object-oriented scripting language that is a dialect of ECMAScript.
- It was originally designed to add interactivity to HTML pages through dynamic HTML, reacting to events, and data validation.
- JavaScript is now heavily used in AJAX-based sites to asynchronously retrieve and display data without reloading pages.
- The document discusses JavaScript compatibility issues and provides examples of basic JavaScript concepts like variables, comparisons, repetition, and popup boxes.
Love it or hate it, JavaScript is playing an increasingly important role in the next generation of web and mobile apps. As code continues to move from the server to the client, JavaScript is being used to do more than simple HTML manipulation. Be prepared for this transition and make sure the JavaScript you write is optimized and ready to perform on desktops and devices! In this session, you will learn ten practical tips that you can use today to write faster, more maintainable, memory friendly JavaScript.
This document provides tips and tricks for using jQuery. It discusses selecting elements by ID or class and the differences in performance. It recommends caching frequently used objects, binding events, and manipulating the DOM in certain ways for better performance. Useful jQuery plugins are also mentioned like Tipsy for tooltips, Nivo Slider for image sliders, and Shadowbox for lightboxes. Best practices like unit testing, benchmarking, and avoiding certain DOM manipulation functions are advised.
This document provides an overview and introduction to jQuery:
1. jQuery is a JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions. It uses CSS-style selectors to select and work with elements in the DOM.
2. To implement jQuery, include the jQuery library file using a <script> tag, then write jQuery code inside <script> tags on the page. jQuery code uses the $ symbol or jQuery keyword to represent the library.
3. Common jQuery methods include selecting elements with CSS-style selectors like $("p"), modifying styles with .css(), handling events with .click(), and animating elements with .animate(). jQuery simplifies
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
The document discusses the goals and design of Zepto.js, a JavaScript framework for mobile web applications. It aims to have a very small codebase that is easy to use, extends native browser APIs, and avoids non-essential browser implementations. It provides a jQuery-like API but takes advantage of mobile features for better performance on small screens and devices with limited bandwidth.
Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
This document discusses best practices for writing JavaScript code, including using object-oriented patterns, object hierarchies, and the prototype property to organize code and prevent naming collisions. It also recommends writing reusable code by parameterizing functions, using object literals as flexible parameters, and loading JavaScript on demand. Additionally, it suggests separating content, CSS and JavaScript into different files and reducing file sizes for production.
The document discusses reactive application patterns and principles. It describes how Akka actors can be used to build message-driven, resilient, elastic, and responsive applications. It provides an example of using Play, Akka Cluster Sharding to build a reactive user management system that is horizontally scalable and always available.
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014Matthias Noback
Events are the new hooks. But what is an event really? How can you best describe an event in your code? What types of events are there, and how do you decide whether or not to implement something as an event?
In this talk we take a look at how events are essential to processing a Request and producing a Response. We take a look at the Symfony EventDispatcher and related classes that you need when you want to hook into this process. When you know all about the event system and how you can implement your own events, we discuss some situations which may or may not be good use cases for events. You will learn to decide if using events is the right solution for your problem.
This document discusses hardened JavaScript and how it can be used to safely run untrusted code. It describes how JavaScript environments like browsers allow arbitrary programs to run but mediate their interactions. It then explains how techniques like freezing objects, compartmentalization, and avoiding direct eval can "harden" JavaScript to prevent malicious code from harming the system or accessing private data. The goal is to allow safe interaction between mutually untrusting code while preventing attacks.
JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element's attribute or to extract HTML code from a paragraph or division.
JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use.
In JS: CLASS <=> Constructor FN
new FN() => FN() { this }
FN = CLASS (FN = FN, FN = DATA)
Objects
Prototype / __proto__
Inheritence
Rewriting / Augmenting
built in objects
JavaScript Fundamentals with Angular and LodashBret Little
The purpose of this presentation is also largely to explain some of the fun parts of JavaScript (dynamic function invocation with reflection, dynamic arguments, etc). I don't necessarily encourage putting complex logic throughout your templates with lodash, though there may be times it is appropriate.
Lets talk about lodash and how it can easily be married to Angular. Using a six line filter, I will expose the power of lodash directly within angular templates. This will be an introduction to lodash, angular templates, and we'll talk about scope and reflection within JavaScript.
He will start you at the beginning and cover prerequisites; setting up your development environment first. Afterward, you will use npm to install react-native-cli. The CLI is our go to tool. We use it to create and deploy our app.
Next, you will explore the code. React Native will look familiar to all React developers since it is React. The main difference between React on the browser and a mobile device is the lack of a DOM. We take a look a many of the different UI components that are available.
With React Native you have access to all of the devices hardware features like cameras, GPS, fingerprint reader and more. So we'll show some JavaScript code samples demonstrating it. We will wrap up the evening by deploying our app to both iOS and Android devices and with tips on getting ready for both devices stores.
The fundamentals and advance application of Node will be covered. We will explore the design choices that make Node.js unique, how this changes the way applications are built and how systems of applications work most effectively in this model. You will learn how to create modular code that’s robust, expressive and clear. Understand when to use callbacks, event emitters and streams.
ECMAScript 5 (ES5) is the 5th edition of the ECMAScript standard. It introduces new meta-level controls like property descriptors to define properties, refinements like making built-ins tamper-proof, and additions to the language API like new methods for strings and arrays. Strict mode helps catch errors and undefined behavior. Support for ES5 varies across browsers.
s React.js a library or a framework? In any case, it is a new way of working that represents a revolution in the way of building web projects. It has very particular characteristics that allow us, for instance, to render React code from the server side, or to include React components from Twig tags. During this talk we will present React.js, we will explore how to take advantage of it from PHP projects and we will give answers to practical problems such as universal (isomorphical) rendering and the generation of React.js forms from Symfony forms without duplication of efforts.
Javascript basics for automation testingVikas Thange
This document provides an overview of basic JavaScript examples and concepts. It covers topics such as writing JavaScript code, variables, conditional statements, functions, loops, events, and error handling. For each topic, it provides short code snippets to demonstrate the concept. It concludes by referencing W3Schools as a resource and thanking the reader.
This document provides an agenda for an introduction to jQuery and jQuery UI. It begins with an overview of selectors, events, traversing, effects & animations, and Ajax in jQuery. It then discusses what jQuery is, its history, advantages over vanilla JavaScript, examples, and the noConflict() method. Next, it covers various selectors, traversing methods, filters, and events. The document concludes with discussions of manipulating HTML and CSS, animations, jQuery's Ajax methods, and integrating jQuery UI.
The document provides information about jQuery:
1) jQuery is an open-source JavaScript library developed by John Resig in 2006 that simplifies HTML document traversal and manipulation, events, animations and Ajax interactions for rapid web development.
2) It is used by many large companies and websites and has two versions: compressed and uncompressed, under both MIT and GPL licenses.
3) The document outlines jQuery's main features including being lightweight, having a large plugin library, easy to learn and use, CSS3 support, documentation and examples. It then provides examples of how to implement jQuery.
This document provides an overview and introduction to jQuery:
1. jQuery is a JavaScript library that simplifies HTML document traversing, event handling, animating, and Ajax interactions. It uses CSS-style selectors to select and work with elements in the DOM.
2. To implement jQuery, include the jQuery library file using a <script> tag, then write jQuery code inside <script> tags on the page. jQuery code uses the $ symbol or jQuery keyword to represent the library.
3. Common jQuery methods include selecting elements with CSS-style selectors like $("p"), modifying styles with .css(), handling events with .click(), and animating elements with .animate(). jQuery simplifies
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
The document discusses the goals and design of Zepto.js, a JavaScript framework for mobile web applications. It aims to have a very small codebase that is easy to use, extends native browser APIs, and avoids non-essential browser implementations. It provides a jQuery-like API but takes advantage of mobile features for better performance on small screens and devices with limited bandwidth.
Workshop JavaScript Testing. Frameworks. Client vs Server Testing. Jasmine. Chai. Nock. Sinon. Spec Runners: Karma. TDD. Code coverage. Building a testable JS app.
Presentado por ing: Raúl Delgado y Mario García
This document discusses best practices for writing JavaScript code, including using object-oriented patterns, object hierarchies, and the prototype property to organize code and prevent naming collisions. It also recommends writing reusable code by parameterizing functions, using object literals as flexible parameters, and loading JavaScript on demand. Additionally, it suggests separating content, CSS and JavaScript into different files and reducing file sizes for production.
The document discusses reactive application patterns and principles. It describes how Akka actors can be used to build message-driven, resilient, elastic, and responsive applications. It provides an example of using Play, Akka Cluster Sharding to build a reactive user management system that is horizontally scalable and always available.
A Series of Fortunate Events - Drupalcon Europe, Amsterdam 2014Matthias Noback
Events are the new hooks. But what is an event really? How can you best describe an event in your code? What types of events are there, and how do you decide whether or not to implement something as an event?
In this talk we take a look at how events are essential to processing a Request and producing a Response. We take a look at the Symfony EventDispatcher and related classes that you need when you want to hook into this process. When you know all about the event system and how you can implement your own events, we discuss some situations which may or may not be good use cases for events. You will learn to decide if using events is the right solution for your problem.
This document discusses hardened JavaScript and how it can be used to safely run untrusted code. It describes how JavaScript environments like browsers allow arbitrary programs to run but mediate their interactions. It then explains how techniques like freezing objects, compartmentalization, and avoiding direct eval can "harden" JavaScript to prevent malicious code from harming the system or accessing private data. The goal is to allow safe interaction between mutually untrusting code while preventing attacks.
JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element's attribute or to extract HTML code from a paragraph or division.
JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use.
In JS: CLASS <=> Constructor FN
new FN() => FN() { this }
FN = CLASS (FN = FN, FN = DATA)
Objects
Prototype / __proto__
Inheritence
Rewriting / Augmenting
built in objects
JavaScript Fundamentals with Angular and LodashBret Little
The purpose of this presentation is also largely to explain some of the fun parts of JavaScript (dynamic function invocation with reflection, dynamic arguments, etc). I don't necessarily encourage putting complex logic throughout your templates with lodash, though there may be times it is appropriate.
Lets talk about lodash and how it can easily be married to Angular. Using a six line filter, I will expose the power of lodash directly within angular templates. This will be an introduction to lodash, angular templates, and we'll talk about scope and reflection within JavaScript.
He will start you at the beginning and cover prerequisites; setting up your development environment first. Afterward, you will use npm to install react-native-cli. The CLI is our go to tool. We use it to create and deploy our app.
Next, you will explore the code. React Native will look familiar to all React developers since it is React. The main difference between React on the browser and a mobile device is the lack of a DOM. We take a look a many of the different UI components that are available.
With React Native you have access to all of the devices hardware features like cameras, GPS, fingerprint reader and more. So we'll show some JavaScript code samples demonstrating it. We will wrap up the evening by deploying our app to both iOS and Android devices and with tips on getting ready for both devices stores.
The fundamentals and advance application of Node will be covered. We will explore the design choices that make Node.js unique, how this changes the way applications are built and how systems of applications work most effectively in this model. You will learn how to create modular code that’s robust, expressive and clear. Understand when to use callbacks, event emitters and streams.
ECMAScript 5 (ES5) is the 5th edition of the ECMAScript standard. It introduces new meta-level controls like property descriptors to define properties, refinements like making built-ins tamper-proof, and additions to the language API like new methods for strings and arrays. Strict mode helps catch errors and undefined behavior. Support for ES5 varies across browsers.
s React.js a library or a framework? In any case, it is a new way of working that represents a revolution in the way of building web projects. It has very particular characteristics that allow us, for instance, to render React code from the server side, or to include React components from Twig tags. During this talk we will present React.js, we will explore how to take advantage of it from PHP projects and we will give answers to practical problems such as universal (isomorphical) rendering and the generation of React.js forms from Symfony forms without duplication of efforts.
Javascript basics for automation testingVikas Thange
This document provides an overview of basic JavaScript examples and concepts. It covers topics such as writing JavaScript code, variables, conditional statements, functions, loops, events, and error handling. For each topic, it provides short code snippets to demonstrate the concept. It concludes by referencing W3Schools as a resource and thanking the reader.
This document provides an agenda for an introduction to jQuery and jQuery UI. It begins with an overview of selectors, events, traversing, effects & animations, and Ajax in jQuery. It then discusses what jQuery is, its history, advantages over vanilla JavaScript, examples, and the noConflict() method. Next, it covers various selectors, traversing methods, filters, and events. The document concludes with discussions of manipulating HTML and CSS, animations, jQuery's Ajax methods, and integrating jQuery UI.
The document provides information about jQuery:
1) jQuery is an open-source JavaScript library developed by John Resig in 2006 that simplifies HTML document traversal and manipulation, events, animations and Ajax interactions for rapid web development.
2) It is used by many large companies and websites and has two versions: compressed and uncompressed, under both MIT and GPL licenses.
3) The document outlines jQuery's main features including being lightweight, having a large plugin library, easy to learn and use, CSS3 support, documentation and examples. It then provides examples of how to implement jQuery.
The document discusses secrets and techniques for JavaScript libraries. It covers topics like the JavaScript language, cross-browser code, events, DOM traversal, styles, animations, distribution, and HTML insertion. It provides examples and explanations of techniques for class creation, timers, options, subclassing, custom events, selector internals, computed styles, and dimension calculations.
The document discusses jQuery, a JavaScript library that simplifies common tasks like accessing and modifying elements on an HTML page. It covers how jQuery interacts with the DOM and allows selecting elements, modifying styles and content, and handling events. The document also provides examples of how jQuery can be used to make AJAX requests to retrieve and display external data without reloading the page.
The document discusses jQuery, a JavaScript library that simplifies HTML document traversal and manipulation, events, animations, and Ajax interactions for rapid web development. It covers key jQuery concepts like selector engines, DOM manipulation methods, event handling, AJAX functionality, and how to create jQuery plugins. The document also provides best practices like using jQuery.noConflict() when other libraries are used, always storing jQuery objects in variables, and following a self-executing function pattern.
The document provides an overview of JavaScript design patterns including creational, structural, and behavioral patterns. It discusses common patterns like the module pattern, prototype pattern, factory pattern, decorator pattern, observer pattern, and more. Code examples are provided to demonstrate how each pattern works in JavaScript.
This document provides an overview and introduction to JavaScript:
- It discusses JavaScript basics like object-based programming, value types, variables, arrays, user-defined objects and functions.
- It describes how to put JavaScript in HTML pages and common built-in objects like window, document and forms.
- It also covers event handling, JavaScript libraries like jQuery, debugging tools like Firebug, and topics like form and DOM manipulation.
This document provides an overview of jQuery, including what it is, why it's useful, how to get started, and some common jQuery syntax. jQuery is a JavaScript library that makes it much easier to use JavaScript on websites. It simplifies tasks like DOM manipulation, event handling, animation, and Ajax. The document explains how to download jQuery, includes some basic jQuery syntax using selectors and methods, and covers various features like effects, HTML/CSS manipulation, events, traversing, and Ajax.
JavaScript is the programming language of the web. It can dynamically manipulate HTML content by changing element properties like innerHTML. Functions allow JavaScript code to run in response to events like button clicks or timeouts. JavaScript uses objects and prototypes to define reusable behaviors and properties for objects. It is an important language for web developers to learn alongside HTML and CSS.
This document contains a summary of jQuery secrets presented by Bastian Feder. It discusses various techniques including saving and removing state from DOM elements using jQuery.data() and jQuery.removeData(), extending jQuery functionality through plugins, and customizing AJAX requests and event handling. The presentation provides code examples for working with jQuery's data storage methods, namespaces, promises/deferreds, global AJAX settings, and extending jQuery.
This document summarizes jQuery secrets presented by Bastian Feder. It discusses utilities like jQuery.data() and jQuery.removeData() for saving and removing state on DOM elements. It also covers AJAX settings, events, extending jQuery, and jQuery plugins. The presentation provides code examples for working with data, events, namespaces, AJAX, and extending jQuery functionality.
Adding a modern twist to legacy web applicationsJeff Durta
Avoid misery of working with legacy code
We will see how you can add independent and isolated components to existing pages; pages that may be difficult to change
React and Flux allow you to make self-contained additions that handle their own data access/persistence
Mobile applications Development - Lecture 12
Javascript
jQuery (Zepto)
useful microframeworks
This presentation has been developed in the context of the Mobile Applications Development course at the Computer Science Department of the University of L’Aquila (Italy).
http://www.di.univaq.it/malavolta
Pick up the low-hanging concurrency fruitVaclav Pech
The document discusses various approaches for dealing with concurrency and parallelism in programming. It highlights that while threads and locks make concurrency difficult, there are better solutions like fork/join pools, dataflow programming, and actors. These approaches allow programmers to write code without worrying about threads and synchronization, making parallelism easier to implement. The key milestone approaches mentioned are asynchronous calculations, parallel collection processing using fork/join, dataflow programming using variables and streams, and using actors to isolate concurrent operations.
J Query The Write Less Do More Javascript Libraryrsnarayanan
This document provides an agenda for a presentation on jQuery, a popular JavaScript library. It begins with an introduction to jQuery and why it is useful, then covers various topics like DOM manipulation, event handling, Ajax, effects, and plugins. It emphasizes that jQuery makes cross-browser JavaScript programming easier and provides robust support for tasks like DOM traversal, Ajax, and animations. The document also includes several code demos to illustrate jQuery concepts.
The document discusses FuseJS, a JavaScript framework that aims to improve performance and compatibility across browsers. It includes sandboxed native objects to prevent namespace pollution, modular builds, and various selector engines. It also details optimizations for quirks mode, events, caching, and performance benchmarks showing FuseJS has lower execution times than other frameworks.
This document discusses closures in JavaScript. It defines a closure as a function together with references to its surrounding state (the lexical environment). Closures are created by inner functions that return references to variables in outer scopes. This allows functions to access variables from outer scopes even after they have returned. Closures are useful for handling events and emulating private methods. While they provide data encapsulation, closures can also negatively impact performance due to increased memory usage.
2. Different species than POCOs Properties added dynamically upon first use A typo creates a new property – yikes! Properties accessed via: Dot notation (Object.Property) Subscript notation (Object[‘Property’]) Literal syntax: varsomeObj = { someProp: ‘some value’, otherProp: 2 }; Variables are properties. Equivalent statements in the global scope: var prop = ‘x’; window.prop = ‘x’; prop = x; Objects in Javascript
3. Functions are also objects Functions can contain other functions! have properties! be assigned to a property be passed to a method and also returned from it Smoke and mirrors. Equivalent statements: function someFunc(someParam) { return ‘wow!’ } someFunc = function(someParam) { return ‘wow!’ } window. someFunc = function(someParam) { return ‘wow!’ } So what’s the deal with these functions?
4. Local variables stick around Great way to avoid using global variables Avoids potential naming conflicts Example: var f = function() { varartifactID = 5553333; return function() { processArtifact(artifactID++); } } And then we found closure…
5. Structure and behavior separated Behavior can change independent of structure Avoids spaghetti code Event handling not performed inline Unobtrusive Javascript
6. Start Assume javascript not available Implement acceptable functionality End Layer javascript goodness on top Implement javascript-enhanced functionality Degrade gracefully when javascript cannot be used Progressive Enhancement
7. jQuery uses CSS-style selectors Creates wrapped sets when passed to jQuery jQuery(‘tr:nth-child(2)’) Alias: $(‘tr:nth-child(2)’) Class selectors slower than ID selectors What’s with these selectors?
8. p > a [all anchor tags, direct children of p tags] div.items a [all anchor tags, descendents of div tags with class of items] div.items:has(a) [all div tags with a class of items that contain anchor tags] a[href^=‘http://’] [all anchor tags, href attribute starts with http://] div#coolness.gunit [all div tags with the id of coolness and class of gunit] Selectors: Child, Container, Attribute
9. table#itemListtr:even[all even rows in the table with an ID of itemList] :checkbox:checked:enabled[all enabled and checked checkboxes] :enabled:visible[all enabled and visible elements] Selectors: Filters
14. Methods on wrapped sets size() => # of elements contained within first(), last() => first or last element within toArray() => array of DOM elements not(exp), filter(exp) => copy of original minus exp exp = selector, function, element, or array slice(begin, end) => subset within the indices each(iterator) => invokes iterator for every element end() => back up to previous wrapped set andSelf() => merges two previous wrapped sets to another Manipulating wrapped sets
15. Browsers implement events differently Event object creation differs Event propagation differs Event handler location differs In other words, it’s great fun! Browser Event Models
16. Handlers defined inline Limit: One handler per event elem.onclick = function(event) { … } Event bubbles up through the DOM Return false to cancel event propagation <form onsubmit=“return false;” … Basic Event Model
17. DOM Level 2 Event Model Allows multiple event handlers per event addEventListener('click', function(event) { ... }, useCapture) useCapture = true => handle capture phase (top to target) event useCapture = false => handle bubble phase (target to top) event Not supported by IE! IE event model uses legacy event names (onclick vs. click) In IE event model, event instance not passed to handler (use window.event) Newer, Fancier Event Model
18. Works on all browsers Allows multiple event handlers per event Uses standard event names Event instance passed as parameter to handler Like Level 2 model but no capture phase Lots of ways to attach handlers to events jQuery Event Model
22. Hijacking form posts Use Ajax POST requests Used in ASP.NET Update Panel jQuery makes it super simple Encourages progressive enhancement The wonderful world of Hijaxing
24. jQuery.event.special.eventName Special Events have these optional methods: setup Executes when first event handler is bound to element teardown Executes when last event handler is bound to element add Executes when each event handler is added to element remove Executes when each event handler is removed from element _default (not that interesting) Executes after event has bubbled to “document” Executes for custom events fired by “trigger” method The Wonders Of Special Events
25. Setup event handlers Calculate width and height Element position Ancestry Progeny Containment Filter and Each Merge and Extend Quick Rundown of jQueryConfusicons
26. bind() attaches handler to all elements in wrapped set bind() allows binding multiple events with a handler live() attaches handler to current and FUTURE elements via DOM Scripting live() binds only one event live() can only be invoked on the ORIGINAL wrapped set $('#item', 'tr').closest('table').live('click', function() { ... }); delegate() attaches handlers for current and FUTURE elements delegate() allows filtering to bind to a subset of wrapped set $('#item').delegate('a', 'click', function() { ... }); Binding Event Handlers
27. css('width') and css('height') return strings e.g. '200px‘ width() and height() return integers width() and height() can return dimensions of window and document css('width') and css('height') throw errors for above css('width') and css('height') not always reliable IE returns ‘auto’ for computed dimensions Width And Height
28. position() calculates the offset from nearest ancestor with relative positioning If none found, defaults to document offset() ALWAYS calculates the offset from document Element Position
29. parent(selector) returns the immediate parent if it matches the selector parents(selector) returns all ancestors that match the selector closest(selector) returns the closest ancestor that matches the selector Ancestry
31. not(selector) returns filtered elements that do not match the selector is(selector) returns true if any element in the wrapped set matches the selector $('p:not(.info)') SAME AS $('p').not(‘.info’) $(‘table:has(tr)’) returns all tables with at least one row Containment
32. filter(selector) returns wrapped set of elements that match the selector filter(function) returns wrapped set of all elements for which the function returns true each(function) executes the function over all elements in the wrapped set $.each(function) runs on any array like object function context set to the current element being processed Filter and Each
33. $.merge() combines 2 arrays and saves result to first array $.extend() combines 2+ objects and saves result to first object jQuery.extend([recursive?], target, object1, ... ) Common idiom to use $.extend() to provide default values function(options) { var settings = $.extend({ prop1: 200, prop2: null, }, options || {} ); } Merge And Extend
34. Simply assign a function to a property on jQuery ($) Good Idea: Namespacing $.kCura = {}; $.kCura.somethingWonderful = function(awesomeness) { … }; Bad Idea: Assume $ has not been appropriated (function($) { // awesome code goes here }) (jQuery); Extending jQuery: Utility Functions
35. Create a property on the fn object of jQuery Function context within main body refers to wrapped set Use each() to work on elements individually If iterating via functions, above iteration automatic $.fn.kCurafy = function() { this.each(function() { makeAwesome($(this).data(‘identifier’)); } function makeAwesome(id) { … } }; Usage Example: $(‘img’).kCurafy(); Extending jQuery: Wrapper Functions