SlideShare a Scribd company logo
James Greene

http://jamesgreene.net/
“Bang, Bang”
     




   (Just kidding!)   2
The Problem
     
  I desire…



              3
WANTED!
                     
$("body").on("textSelect", function($event) {
    console.log("Text was selected!");
});




              DEAD OR ALIVE

                                            4
Cheesy!
                  
$("body").on("textSelect", function($event) {
    console.log("Text was selected!");
});

$("body").on("mouseup", function($event) {
  if (window.getSelection().rangeCount > 0) {
    $("body").trigger("textSelect");
  }
}

                                            5
Better…?
                  
$.fn.onTextSelect = function(callback) {
  this.on("mouseup", function($event) {
    if (window.getSelection().rangeCount > 0) {
      callback($event);
    }
  }
}

$("body").onTextSelect(function($event) {
    console.log("Text was selected!");
});
                                                  6
jQuery Event System
        
   Special Events API



                        7
Brief History
                 
 jQuery 1.3:
   Special Events API
   …but no official documentation


 jQuery 1.7:
   Major overhaul to Special Events API
   …but still no official documentation


 Official documentation? Now in progress….
                                              8
Responsibilities
              
1. Allow hooks for “fixing” events

2. Allow for creation of custom events
     ready
     mouseenter
     mouseleave
     *
                                         9
Custom Event: Syntax #1
         
 $.event.special.MyEvent = {
     noBubble: false,
     bindType: "otherEventType",
     delegateType: "otherEventType",
     handle: function($event, data) { … },
 };


NOTE: Almost all of these are optional to set (in varying combinations).
                                                                           10
Custom Event: Syntax #2
          
$.event.special.MyEvent = {
    noBubble: false,
    setup: function(data, namespaces, handler) { … },
    teardown: function() { … },
    add: function(handleObj) { … },
    remove: function(handleObj) { … },
    trigger: function($event, data) { … },
    _default: function($event, data) { … }
};


NOTE: Almost all of these are optional to set (in varying combinations).
                                                                           11
Demo Time
       
Making the magic happen!



                           12
Demo #1: multiclick
           
 Usage:
    $(…).on("multiclick", { clicks: 3 },
         function($event) {
             console.log("Thrice!");
         }
    );

 Demo pages:
   Basic
   Nested elements
 Code:
   http://github.com/JamesMGreene/jquery.multiclick/   13
Demo #2: textSelect
           
 Usage:
    $(…).on("textSelect", function($event) {
         console.log("Text was selected!");
    });

 Demo page:
   Basic

 Code:
   http://github.com/JamesMGreene/jquery.textSelect/



                                                        14
Demo #3: swipe
            

throw new RangeError(
  "A demo does not exist at this index");




                                       15
Aftermath
    
Lessons Learned



                  16
Lessons Learned
            

               Surprise!
Textual selection event was added to IE9+.
Sort of….



                                             17
Lessons Learned
              
Special Events API is a dependency of
jQuery Mobile:
     tap
     scrollstart / scrollstop
     swipe / swipeleft / swiperight
     orientationchange
     throttledresize

                                        18
Questions?
   




   James Greene
http://jamesgreene.net/
                          19

More Related Content

What's hot (20)

PPT
Kick start with j query
Md. Ziaul Haq
 
PDF
How kris-writes-symfony-apps-london
Kris Wallsmith
 
PDF
How Kris Writes Symfony Apps
Kris Wallsmith
 
PDF
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
PDF
Mulberry: A Mobile App Development Toolkit
Rebecca Murphey
 
PDF
PuppetCamp SEA 1 - Version Control with Puppet
Walter Heck
 
PDF
Dojo Confessions
Rebecca Murphey
 
PDF
Building Large jQuery Applications
Rebecca Murphey
 
PDF
No excuses, switch to kotlin
Thijs Suijten
 
PPTX
Nodejs do teste de unidade ao de integração
Vinícius Pretto da Silva
 
PDF
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 
PPTX
Getting classy with ES6
Andy Sharman
 
PDF
jQuery secrets
Bastian Feder
 
PDF
How to work with legacy code
Michał Kruczek
 
PDF
How to work with legacy code PHPers Rzeszow #2
Michał Kruczek
 
PDF
An Introduction to Jquery
Phil Reither
 
DOCX
Karan chanana
karan chanana
 
PPTX
Taming that client side mess with Backbone.js
Jarod Ferguson
 
PDF
JavaScript patterns
Norihito YAMAKAWA
 
PDF
Using Templates to Achieve Awesomer Architecture
Garann Means
 
Kick start with j query
Md. Ziaul Haq
 
How kris-writes-symfony-apps-london
Kris Wallsmith
 
How Kris Writes Symfony Apps
Kris Wallsmith
 
jQuery: Events, Animation, Ajax
Constantin Titarenko
 
Mulberry: A Mobile App Development Toolkit
Rebecca Murphey
 
PuppetCamp SEA 1 - Version Control with Puppet
Walter Heck
 
Dojo Confessions
Rebecca Murphey
 
Building Large jQuery Applications
Rebecca Murphey
 
No excuses, switch to kotlin
Thijs Suijten
 
Nodejs do teste de unidade ao de integração
Vinícius Pretto da Silva
 
Cleaner, Leaner, Meaner: Refactoring your jQuery
Rebecca Murphey
 
Getting classy with ES6
Andy Sharman
 
jQuery secrets
Bastian Feder
 
How to work with legacy code
Michał Kruczek
 
How to work with legacy code PHPers Rzeszow #2
Michał Kruczek
 
An Introduction to Jquery
Phil Reither
 
Karan chanana
karan chanana
 
Taming that client side mess with Backbone.js
Jarod Ferguson
 
JavaScript patterns
Norihito YAMAKAWA
 
Using Templates to Achieve Awesomer Architecture
Garann Means
 

Viewers also liked (13)

PPT
FOTOGRAFIAS VELEROS REGATAS
Pedro Portillo Strempel
 
PPTX
Oral presentation
ygz4364
 
PPT
Parts of speech
Divzy
 
PPT
Long Island Dental Implant Surgeon presents "Select Dental Implant Clinical D...
Edward Brant DDS, MS
 
PPT
Long Island Periodontist presents "Appropriate Use of Antibiotics In Dentistry"
Edward Brant DDS, MS
 
PPT
Long Island Implant Dentist presents "The Benefits of Dental Implants"
Edward Brant DDS, MS
 
PPT
Long Island Dental Implant Surgeon presents "Introduction To Computer Guieded...
Edward Brant DDS, MS
 
PPT
23576671 presentation
tasteamit37
 
PDF
Long Island Periodontist presents "The Art and Science of the Painless Dental...
Edward Brant DDS, MS
 
PDF
Long Island Dental Specialist aka Periodontist uses Laser Periodontal Surgery...
Edward Brant DDS, MS
 
PPT
Aap ridge split new orleans
Edward Brant DDS, MS
 
PPT
Long Island Periodontist presents "Dental Implant Abutment Impression and Del...
Edward Brant DDS, MS
 
PDF
Faces of-wellness
medfit
 
FOTOGRAFIAS VELEROS REGATAS
Pedro Portillo Strempel
 
Oral presentation
ygz4364
 
Parts of speech
Divzy
 
Long Island Dental Implant Surgeon presents "Select Dental Implant Clinical D...
Edward Brant DDS, MS
 
Long Island Periodontist presents "Appropriate Use of Antibiotics In Dentistry"
Edward Brant DDS, MS
 
Long Island Implant Dentist presents "The Benefits of Dental Implants"
Edward Brant DDS, MS
 
Long Island Dental Implant Surgeon presents "Introduction To Computer Guieded...
Edward Brant DDS, MS
 
23576671 presentation
tasteamit37
 
Long Island Periodontist presents "The Art and Science of the Painless Dental...
Edward Brant DDS, MS
 
Long Island Dental Specialist aka Periodontist uses Laser Periodontal Surgery...
Edward Brant DDS, MS
 
Aap ridge split new orleans
Edward Brant DDS, MS
 
Long Island Periodontist presents "Dental Implant Abutment Impression and Del...
Edward Brant DDS, MS
 
Faces of-wellness
medfit
 
Ad

Similar to Leveraging jQuery's Special Events API (JSConf 2012) (20)

PPT
jQuery 1.7 Events
dmethvin
 
PDF
Writing Maintainable JavaScript
Andrew Dupont
 
PDF
DOM Scripting Toolkit - jQuery
Remy Sharp
 
PDF
The Beauty of Java Script
Michael Girouard
 
PDF
Remy Sharp The DOM scripting toolkit jQuery
deimos
 
PPTX
Spin Up Desktop Apps with Electron.js
Steve Godin
 
PPTX
Scientific calcultor-Java
Shaibal Ahmed
 
PDF
The Beauty Of Java Script V5a
rajivmordani
 
PPTX
Jquery optimization-tips
anubavam-techkt
 
PDF
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Robert Nyman
 
PDF
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
Robert Nyman
 
PDF
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
Robert Nyman
 
PDF
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman
 
PDF
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 
KEY
Special Events: Beyond Custom Events
Brandon Aaron
 
PDF
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Robert Nyman
 
KEY
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
PDF
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
Robert Nyman
 
PDF
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 
PDF
jQuery secrets
Bastian Feder
 
jQuery 1.7 Events
dmethvin
 
Writing Maintainable JavaScript
Andrew Dupont
 
DOM Scripting Toolkit - jQuery
Remy Sharp
 
The Beauty of Java Script
Michael Girouard
 
Remy Sharp The DOM scripting toolkit jQuery
deimos
 
Spin Up Desktop Apps with Electron.js
Steve Godin
 
Scientific calcultor-Java
Shaibal Ahmed
 
The Beauty Of Java Script V5a
rajivmordani
 
Jquery optimization-tips
anubavam-techkt
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
Robert Nyman
 
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman
 
JavaScript APIs - The Web is the Platform - .toster conference, Moscow
Robert Nyman
 
Special Events: Beyond Custom Events
Brandon Aaron
 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Robert Nyman
 
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 
jQuery secrets
Bastian Feder
 
Ad

Recently uploaded (20)

PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 

Leveraging jQuery's Special Events API (JSConf 2012)

  • 2. “Bang, Bang”  (Just kidding!) 2
  • 3. The Problem  I desire… 3
  • 4. WANTED!  $("body").on("textSelect", function($event) { console.log("Text was selected!"); }); DEAD OR ALIVE 4
  • 5. Cheesy!  $("body").on("textSelect", function($event) { console.log("Text was selected!"); }); $("body").on("mouseup", function($event) { if (window.getSelection().rangeCount > 0) { $("body").trigger("textSelect"); } } 5
  • 6. Better…?  $.fn.onTextSelect = function(callback) { this.on("mouseup", function($event) { if (window.getSelection().rangeCount > 0) { callback($event); } } } $("body").onTextSelect(function($event) { console.log("Text was selected!"); }); 6
  • 7. jQuery Event System  Special Events API 7
  • 8. Brief History   jQuery 1.3:  Special Events API  …but no official documentation  jQuery 1.7:  Major overhaul to Special Events API  …but still no official documentation  Official documentation? Now in progress…. 8
  • 9. Responsibilities  1. Allow hooks for “fixing” events 2. Allow for creation of custom events  ready  mouseenter  mouseleave  * 9
  • 10. Custom Event: Syntax #1  $.event.special.MyEvent = { noBubble: false, bindType: "otherEventType", delegateType: "otherEventType", handle: function($event, data) { … }, }; NOTE: Almost all of these are optional to set (in varying combinations). 10
  • 11. Custom Event: Syntax #2  $.event.special.MyEvent = { noBubble: false, setup: function(data, namespaces, handler) { … }, teardown: function() { … }, add: function(handleObj) { … }, remove: function(handleObj) { … }, trigger: function($event, data) { … }, _default: function($event, data) { … } }; NOTE: Almost all of these are optional to set (in varying combinations). 11
  • 12. Demo Time  Making the magic happen! 12
  • 13. Demo #1: multiclick   Usage: $(…).on("multiclick", { clicks: 3 }, function($event) { console.log("Thrice!"); } );  Demo pages:  Basic  Nested elements  Code:  http://github.com/JamesMGreene/jquery.multiclick/ 13
  • 14. Demo #2: textSelect   Usage: $(…).on("textSelect", function($event) { console.log("Text was selected!"); });  Demo page:  Basic  Code:  http://github.com/JamesMGreene/jquery.textSelect/ 14
  • 15. Demo #3: swipe  throw new RangeError( "A demo does not exist at this index"); 15
  • 16. Aftermath  Lessons Learned 16
  • 17. Lessons Learned  Surprise! Textual selection event was added to IE9+. Sort of…. 17
  • 18. Lessons Learned  Special Events API is a dependency of jQuery Mobile:  tap  scrollstart / scrollstop  swipe / swipeleft / swiperight  orientationchange  throttledresize 18
  • 19. Questions?  James Greene http://jamesgreene.net/ 19

Editor's Notes

  • #2: Hello! My name is James “Gunslinger” Greene and I’m going to be talking to you today about leveraging jQuery’s Special Events API to extend the event system with your own custom events.Oh, hey, quick side note: did you guys already hear the secret password for getting into the Red Revolver Lounge tonight?
  • #3: Just kidding! There is no secret password — at least not that anyone told me about. 
  • #4: So, let’s talk about the problem that led me to stumble upon jQuery’s Special Events API.
  • #5: What I wanted was a way for both myself and other JavaScript consumers to bind to synthetic events that don’t have to manually trigger. In particular, I was seeking an event that would fire on text selection. Alas, my initial searches yielded unfortunate results: even modern browsers don’t seem to support such an event.†  †More on this later. So, we have some alternative options....
  • #6: First, we could attach to the relevant corresponding DOM event (mouseup, in this case) with a callback that manually triggers a synthetic “textSelect” event when appropriate. This is bit cheesy, plus I really don’t want to have to hook up an event like this each time.
  • #7: Perhaps better: I could wrap this same basic code up as a simple jQuery plugin. However, I still think this ugly AND I was given recent direction from the jQuery Foundation discouraging jQuery plugin functions for event-related shortcuts.
  • #8: Let’s dive in and take a closer look at jQuery’s Special Events API.
  • #9: jQuery 1.3 introduced a rudimentary form of the Special Events API.jQuery 1.7 introduced a major overhaul to the long-neglected Special Events API. This revamped API is the true basis of my talk today.An important disclaimer, though: this API is still under review and therefore still subject to change. Proceed with caution!
  • #10: So what doesjQuery’s Special Events API do?The Special Events API has two main responsibilities: 1. Allow hooks for “fixing” events. This is primarily to standardize event behavior across browsers. 2. Allow for the creation of custom events defined by the browsers. This includes the ultra-famous “ready” event that we all know and love, as well as “mouseenter” and “mouseleave”… but it doesn’t have to stop there! This also allows developers to create their own custom bindable events that snap right into the jQuery Event System for a smooth, integrated feeling. This is where the rest of the talk will focus.
  • #11: The API for custom events has a number of properties and methods that can be set. In practice, however, most of them are optional or must be used in combinations. A quick rundown of each: - noBubble: Indicates whether or not this event type should be bubbled when the .trigger() method is called; defaults to false, which enables bubbling. - bindType and delegateType: Specify that a special event should be handled like another event type until the event is delivered; bindType if attached directly, delegateType for delegated events. - handle: The handle hook is basically a pre-condition checker. If the handle hook exists, jQuery calls it INSTEAD OF the attached event handler, passing it the event and any data passed from .trigger() if it was not a native event. Based in the information it has, the handle hook should decide whether to call the original handler function.
  • #12: The API for custom events has a number of properties and methods that can be set. In practice, however, most of them are optional or must be used in combinations. A quick rundown of each: - noBubble: Same as on the previous slide! - setup: Called the first time an event of a particular type is attached to an element. - teardown: Called when the final event of a particular type is removed from an element. - add: Called each time an event handler is added to an element. - remove: Called each time an event handler is removed from an element. - trigger: Called when the .trigger() or .triggerHandler() methods are used to trigger an event for the special type from code, as opposed to events that originate from within the browser. - _default: When the .trigger() method finishes running all the event handlers for an event, it also looks for and runs any method on the target object by the same name unless at least one of the handlers called event.preventDefault(). The _default hook is called just prior to checking for and executing the element's default method; sort of a last-chance event handler for jQuery.
  • #13: Alright, so enough background: let’s see what this API can do. Demo time!
  • #14: Note: This demo will show off Syntax #1.
  • #15: Note: This demo will show off Syntax #2.
  • #16: Whoops! As you can see,I didn’t have time to create the basic “swipe” demo that I had planned… but that’s OK. Another comment on that later.
  • #17: Alright, so I think this is a pretty handy API for allowing us to abstract creative custom events that we consider to be missing. But, I also want to share with you a few other things I learned in the process.
  • #18: Surprise! IE turns out to be the dark horse innovators for JavaScript once again, introducing an updated version of the “select” event that kind of supports this behavior. The issue with it? The deepest element reference you can get to it is the body element. Sadness.
  • #19: When I decided to start updating my “textSelect” event for mobile, I decided to look at jQuery Mobile’s source code to find out what test they do to detect support for touch events. In doing so, I found another missing link: jQuery Mobile is loaded with usage of the Special Events API. They use it to abstract out the many custom event types you see on this slide. Should’ve drawn this connection earlier, but all the same, it was nice to discover that the API receives more usage than I originally thought.
  • #20: Thanks for coming to my talk! Are there any questions?