Understanding jQuery Events

& working with new HTML5 APIs

( gul.ly/10x )

bocoup

bocoup

Boaz Sender

boazsender.com
github.com/boazsender
@boazsender
boaz on freenode (/msg boaz)

The event object

Passed to your event callback

.targeted
    window.addEventListener('eventtype', function( eventObj ){
      // do stuff with your event object
    });

    $(elem).bind('eventtype', function( eventObj ){
      // do stuff with your event object
    });

    $('.targeted').click(function( eventObj ){
      // do stuff with your event object
      console.log( eventObj.target )
    });
  

But...

jQuery clobbers ur new props

    $(elem).bind('☺_video_☆_capture__☆_event_☺', function( event ){
      
      event.videoBuffer // nope
      event.videoBuffer // nope
      
    });
  

You need to look at

The originalEvent

Original Gangster 1

It's on the event object

    $(elem).bind('☺_video_☆_capture__☆_event_☺', function( event ){
      
      event.originalEvent.videBuffer // mhmmm
      
    });
  

This is also true for the plain old events you're used to

.clicklogger

    $('.clicklogger').click(function( event ){
    
      var extraProps = [];
    
      $.each( event.originalEvent, function( index, prop ){
        if ( ! event[ index ] ) {
            extraProps.push( index )
        }
      })
    
      console.log("event:", event)
      console.log("original event:", event.originalEvent)
      console.log("extra props", extraProps)
    
    })
  

“click” (MouseEvent)

MDC Click, MDC MouseEvent


    // Native DOM interface
    window.addEventListener('click', function(){ ... });
    
    // jQuery interface
    $(elem).bind('click', function(){ ... });
    
    // jQuery shorthand interface
    $(elem).click(function(){ ... });

  

New HTML5 Events

“hashchange" (HashChangeEvent)

MDC HashChangeEvent, jQuery Hashchange Plugin [source]


    // Native DOM interface
    window.addEventListener( 'hashchange', function(){ ... } )

    // jQuery interface
    $(window).bind( 'hashchange', function(){ ... } )

    // jQuery Hashchange Plugin interface
    $(window).hashchange( function(){ ... } )

  

“popstate" (PopStateEvent)

MDC Popstate


    // Native DOM interface
    window.addEventListener( 'popstate', function(){ ... } );

    // jQuery interface
    $(window).bind( 'popstate', function(){ ... } );

  

“message" (MessageEvent)


    // Native DOM interface
    window.addEventListener( 'message', function(){ ... } )    

    // jQuery interface
    $(window).bind( 'message', function(){ ... } )

  

“message" (MessageEvent) Post/Recieve

MDC PostMessage}

.popupDemo

    $('.popupDemo').click(function(){
      // Make a Popup
      var popup = window
        .open(
          "http://localhost:8888/talks/understanding-jquery-events/popup.html",
          "Bocoup", 
          "width=400,height=800"
        );

      setTimeout(function(){

        popup
          .postMessage(
            "Marco",
            "http://localhost:8888/talks/understanding-jquery-events/popup.html"
          );

      }, 1000)// Send a message to the Popup

      // Listen to messages from the popup
      $(window).bind('message', function( event ){
        console.log( event.originalEvent.data )
      });

  

“message" (MessageEvent) Recieve/Post

MDC PostMessage}


    // What's in the popup
    $(window).bind('message', function( event ){

      $('body').html( event.originalEvent.data )

      event.originalEvent.source
        .postMessage(
          event.originalEvent.data + "? well, polo",
          event.originalEvent.origin
        );

    });

  

“drop" (MouseEvent)


    // Native DOM interface
    window.addEventListener( 'drop', function(){ ... } )    

    // jQuery interface
    $(window).bind( 'drop', function(){ ... } )

  

“drop" (MouseEvent)

MDC Drag & Drop

Drop Here

    var dropzone = $('#dropzone')
        .bind('dragenter', function( event ){
          event.stopPropagation();
          event.preventDefault();
          $('#tank').css('background', '#061552');
        })
        .bind('dragover', function(){
          $('#tank').css('background', '#248aba');
        })
        .bind( 'drop', function( event ) {
          event.stopPropagation();
          event.preventDefault();

          var files = event.originalEvent.dataTransfer.files;
          
          $.each( files, function(index, file){
            var fileReader = new FileReader();
                fileReader.onload = (function(file) {
                   return function( event ) { 
                     $('#tank').html( file.fileName + 
                     '
' + '<img src=' + event.target.result + '></p>') }; })(file); fileReader.readAsDataURL(file); }); });

“timeupdate" (Event)

W3C Media Events Test Page, MDC Media Events List, Popcorn.js


    // Native DOM interface
    document
      .getElementById('video')
      .addEventListener('timeupdate', function(e){ ... })

    // jQuery interface
    $('#video').bind('timeupdate', function(){ ... })

  

“timeupdate" (Event)

timeStamp:


    $('#video').bind('timeupdate', function( event ){
      console.log( event )
    })

  

"MozAudioAvailable" (Event)

MDC


    // Native DOM interface
    document
      .getElementById( 'audio' )
      .addEventListener( 'MozAudioAvailable', function(){ ... });

    // jQuery interface
    $('audio').bind( 'MozAudioAvailable', function(){ ... });

  

“MozAudioAvailable" (Event)

    $('#audio').bind('timeupdate', function( event ){
      console.log( event )
    })
  

There is another way

jQuery.event.props << exists!

Line 450, event.js

    props: "altKey attrChange attrName bubbles button" + 
    "cancelable charCode clientX clientY ctrlKey currentTarget" +
    "data detail eventPhase fromElement handler keyCode layerX" +
    "layerY metaKey newValue offsetX offsetY pageX pageY" +
    "prevValue relatedNode relatedTarget screenX screenY" +
    "shiftKey srcElement target toElement view wheelDelta" +
    "which".split(" "),

    for ( var i = this.props.length, prop; i; ) {
      prop = this.props[ --i ];
      event[ prop ] = originalEvent[ prop ];
    }
  

Add urFaveProp

    jQuery.event.props.push( 'dataTransfer' );
  

But actually don't

New Event Hooks idea for 1.7

jQuery Event Hooks Ticket


    jQuery.event.props["drop"] = { dataTransfer: undefined };

    console.log( jQuery.event.props );

    console.log( jQuery.event.props[ 'drop' ] );  

  

Good resource

Thank You

Boaz Sender

Bocoup 200