SlideShare a Scribd company logo
1 of 21
jQuery: Events, Animation, Ajax
jQuery Events: .one()




// event will be handled only once
$("#do").one("click", function () {
    alert("Done!");
    $(this).text("Can't do it :(");
});


                        http://jsfiddle.net/jsfiddlr/CCr5T/
jQuery Events: .bind()




// one handler for multiple events
$("#field").bind("focus blur", function() {
    $(this).toggleClass("active");
});




                           http://jsfiddle.net/jsfiddlr/gE2dk/
jQuery Events: .bind()



  // multiple handlers per call
  $("#field").bind({
      click: function () {
          $("#echo").empty();
      },
      keyup: function () {
          $("#echo").text($(this).val());
      }
  });

                            http://jsfiddle.net/jsfiddlr/U7jF9/
jQuery Events: .live()


// event will be handled only within context
$("p", $("#c2")[0]).live("click", function () {
    alert("P");
});

// document-wide handling
$("p.alt").live("click", function () {
    alert("P.ALT");
});


                              http://jsfiddle.net/jsfiddlr/bruQc/
jQuery Events: .trigger()


// triggers custom event with parameters
$("#edit").click (function () {
    var text = $("#text");
    var original = text.text();
    text.text("Some another text.");
    text.trigger("edited", [original, 10]);
});

// handles custom event with parameters
$("#text").bind("edited", function (event, original, revision) {
    alert(original + " (rev: " + revision + ")");
});

                                        http://jsfiddle.net/jsfiddlr/vw5E8/
jQuery Events: event.result



// returns custom result
$("h1").click(function () {
    return 10;
});

// uses custom result returned by previous handler
$("h1, h2").click(function (event) {
    alert(event.result);
});




                                http://jsfiddle.net/jsfiddlr/CnFY9/
jQuery Events: .remove()/.detach()

   // removes first para and detaches second
   // then appends them back to body
   $("#do").click(function () {
       // handlers are removed too
       p1.remove();
       // handlers are kept untouched
       p2.detach();

         $("body").append(p1).append(p2);
   });

   p1.click(function () { alert("First"); });
   p2.click(function () { alert("Second"); });

                                  http://jsfiddle.net/jsfiddlr/Yq9pM/
jQuery Events: namespaces
   // just another one ordinary handler
   text.click(function () { alert("?"); });

   // namespaced event handler
   text.bind("click.me", function () {
       // will be fired on "click" and "click.me"
       alert("I am!");
   });

   // multiple namespaced events handler
   // (not nested, but multiple namespaces)
   text.bind("click.me.you", function () {
       // will be fired on "click", "click.me" and/or "click.you"
       alert("I am! You are too!");
   });

   // another handler of couple of namespaced events
   text.bind("mouseover.me mouseout.me",function() {
       $(this).toggleClass("active");
   });
                                           http://jsfiddle.net/jsfiddlr/4L3Fc/
jQuery Events: namespaces
 // triggers non-namespaced event only
 $("#click").click(function () { text.trigger("click!"); });

 // triggers namespaced event
 $("#click-me").click(function () { text.trigger("click.me"); });

 // triggers namespaced event
 $("#click-you").click(function () { text.trigger("click.you"); });

 // unbinds certain event in certain namespace
 $("#unbind-click-me").click(function () {
     // profit? delete only certain handlers, not all
     text.unbind("click.me");
 });

 // unbinds all events in certain namespace
 $("#unbind-me").click(function () {
     // or all namespace members
     text.unbind(".me");
 });                                        http://jsfiddle.net/jsfiddlr/4L3Fc/
jQuery Animation: .stop()
    // drawback is that if user opens/closes "A"
    // there will be no effect
    // until previous animation finished

    $("#open-a").click(function () {
        $("#a").animate({
            height: "80px"
        }, 2000, "linear");
    });

    $("#close-a").click(function () {
        $("#a").animate({
            height: "0"
        }, 2000, "linear");
    });
                                       http://jsfiddle.net/jsfiddlr/48uEK/
jQuery Animation: .stop()
  // here is solution demonstrating .stop()
  // and certain easing (currently "swing")

  $("#open-b").click(function () {
      $("#b").stop(true, true).animate({
          height: "80px"
      }, duration, easing);
  });

  $("#close-b").click(function () {
      $("#b").stop(true, false).animate({
          height: "0"
      }, duration, easing);
  });                            http://jsfiddle.net/jsfiddlr/48uEK/
jQuery Animation: .stop()


// another solution (maybe more appropriate),
// but example wasn't about this

$("#open-a, #close-a").click(function () {
    var div = $("#a");
    if (div.is(":animated")) {
        return;
    }
    div[div.is(":visible") ? "fadeOut" :"fadeIn"](duration);
});




                                     http://jsfiddle.net/jsfiddlr/48uEK/
jQuery Animation: .queue()


  // intention: smoothly show element
  // and then remove it from the DOM
  $("#b1").click(function () {

        // element gets removed before
        // animation finishes
        $("#a")
            .fadeIn(duration)
            .remove();

  });
                             http://jsfiddle.net/jsfiddlr/EXNj9/
jQuery Animation: .queue()

// solution: use animation queue
$("#b2").click(function () {

   $("#b")
       .fadeIn(duration)
       .queue(function(next) {
           $(this).remove();
           // common pattern is to enable execution of
           // other animations (added after .queue() call)
           // by calling the next one
           // (in our example we could omit this)
           next();
       });

                                    http://jsfiddle.net/jsfiddlr/EXNj9/
jQuery Ajax: .ajaxStart()
$(this)

          // show spinner at ajax start
          .ajaxStart(function() {
              $(this).html(
              $("#spinner").clone().show());
          })

          // load content via ajax
          // when loaded it will replace spinner
          .load("/echo/html/", {
              html: "<h1>I've just loaded!</h1>",
              delay: 3
          });
                                  http://jsfiddle.net/jsfiddlr/t38Rx/
jQuery Ajax: .ajaxPrefilter()




// if URL contains "some" then fake request will be executed
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (options.url.indexOf("some") >= 0) {
        options.dataTypes = ["fake"];
    }
});




                                     http://jsfiddle.net/jsfiddlr/VB9ur/
jQuery Ajax: .ajaxTransport()
 // setting transport for "fake" request
 $.ajaxTransport("fake", function(options, originalOptions, jqXHR) {

    // if previous request with certain URL is finished
    // then process this one
    if (urls.indexOf(options.url) === -1) {

        urls += options.url;
        return {
            send: function(headers, completeCallback) {
                setTimeout(function() {
                    urls = urls.replace(options.url, "");
                    completeCallback(200, "success", {
                        "fake": "Success!"
                    });
                }, 5000);
            },
            abort: function () {
            }
        };                                  http://jsfiddle.net/jsfiddlr/VB9ur/
jQuery Ajax: .ajaxTransport()


// otherwise alert error and send "server error" code
    } else {

       alert("Can't call same URL while waiting for response!" );
       return {
           send: function (headers, completeCallback) {
               completeCallback(500, "error");
           },
           abort: function () {
           }
       };

   }

                                         http://jsfiddle.net/jsfiddlr/VB9ur/
Thanks!




                  Thanks for attention and patience! 




                                                 constantin.titarenko@binary-studio.com
                                                     constantin.titarenko@gmail.com
October 4, 2011                                    http://about.me/constantin.titarenko
business, evolved.

More Related Content

What's hot

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
Rebecca Murphey
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
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
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
Robert Nyman
 
Leave No One Behind with HTML5 - FFWD.PRO, Croatia
Leave No One Behind with HTML5 - FFWD.PRO, CroatiaLeave No One Behind with HTML5 - FFWD.PRO, Croatia
Leave No One Behind with HTML5 - FFWD.PRO, Croatia
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
Robert Nyman
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
Robert Nyman
 

What's hot (20)

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
DrupalCon jQuery
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQuery
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
An Introduction to Jquery
An Introduction to JqueryAn Introduction to Jquery
An Introduction to Jquery
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development Toolkit
 
A New Baseline for Front-End Devs
A New Baseline for Front-End DevsA New Baseline for Front-End Devs
A New Baseline for Front-End Devs
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao PauloJavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Sao Paulo
 
YUI 3
YUI 3YUI 3
YUI 3
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos AiresJavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
JavaScript APIs - The Web is the Platform - MDN Hack Day - Buenos Aires
 
Leave No One Behind with HTML5 - FFWD.PRO, Croatia
Leave No One Behind with HTML5 - FFWD.PRO, CroatiaLeave No One Behind with HTML5 - FFWD.PRO, Croatia
Leave No One Behind with HTML5 - FFWD.PRO, Croatia
 
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos AiresJavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
JavaScript APIs - The Web is the Platform - MozCamp, Buenos Aires
 
Dojo Confessions
Dojo ConfessionsDojo Confessions
Dojo Confessions
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, ChileJavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
JavaScript APIs - The Web is the Platform - MDN Hack Day, Santiago, Chile
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of Testing
 
YUI on the go
YUI on the goYUI on the go
YUI on the go
 
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, MontevideoJavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
JavaScript APIs - The Web is the Platform - MDN Hack Day, Montevideo
 

Viewers also liked

Dispositivos de entrada
Dispositivos de entradaDispositivos de entrada
Dispositivos de entrada
patiluki
 
Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008
ntrung
 
Program book 2013
Program book 2013Program book 2013
Program book 2013
otakuthon
 
Jeffrey Sachs
Jeffrey SachsJeffrey Sachs
Jeffrey Sachs
rosiem7
 
Presentations tips
Presentations tipsPresentations tips
Presentations tips
rioulrich
 

Viewers also liked (20)

Jst part1
Jst part1Jst part1
Jst part1
 
The Power of BIG OER
The Power of BIG OERThe Power of BIG OER
The Power of BIG OER
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
 
Dispositivos de entrada
Dispositivos de entradaDispositivos de entrada
Dispositivos de entrada
 
Class 2 unit 8 can you help me please
Class 2 unit 8 can you help me pleaseClass 2 unit 8 can you help me please
Class 2 unit 8 can you help me please
 
II Kongres eHandlu: Piotr Chmielewski, Social Media Now - "Kampanie reklamowe...
II Kongres eHandlu: Piotr Chmielewski, Social Media Now - "Kampanie reklamowe...II Kongres eHandlu: Piotr Chmielewski, Social Media Now - "Kampanie reklamowe...
II Kongres eHandlu: Piotr Chmielewski, Social Media Now - "Kampanie reklamowe...
 
Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008
 
Memuary Tetrad 1
Memuary Tetrad 1Memuary Tetrad 1
Memuary Tetrad 1
 
Program book 2013
Program book 2013Program book 2013
Program book 2013
 
Jeffrey Sachs
Jeffrey SachsJeffrey Sachs
Jeffrey Sachs
 
Groasis Waterboxx - Popular Science Winner of Best of What's New in 2010
Groasis Waterboxx - Popular Science Winner of Best of What's New in 2010Groasis Waterboxx - Popular Science Winner of Best of What's New in 2010
Groasis Waterboxx - Popular Science Winner of Best of What's New in 2010
 
Better Biz Dev – Music Startup Academy Denver - October 8, 2015
Better Biz Dev – Music Startup Academy Denver - October 8, 2015Better Biz Dev – Music Startup Academy Denver - October 8, 2015
Better Biz Dev – Music Startup Academy Denver - October 8, 2015
 
Chance challenge change Arise Roby
Chance challenge change   Arise RobyChance challenge change   Arise Roby
Chance challenge change Arise Roby
 
Presentations tips
Presentations tipsPresentations tips
Presentations tips
 
Concumer behavior
Concumer behaviorConcumer behavior
Concumer behavior
 
Rtp 83 permentan ot.140 6 2014
Rtp 83 permentan ot.140 6 2014Rtp 83 permentan ot.140 6 2014
Rtp 83 permentan ot.140 6 2014
 
SE3221 - Playing the Glong Yao
SE3221 - Playing the Glong YaoSE3221 - Playing the Glong Yao
SE3221 - Playing the Glong Yao
 
2008111807581919
20081118075819192008111807581919
2008111807581919
 
Technological applications and innovations
Technological applications and innovationsTechnological applications and innovations
Technological applications and innovations
 
Saran makalah kb
Saran makalah kbSaran makalah kb
Saran makalah kb
 

Similar to jQuery: Events, Animation, Ajax

international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
rajivmordani
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Robert Nyman
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
baygross
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Remy Sharp
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
Robert Nyman
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 

Similar to jQuery: Events, Animation, Ajax (20)

jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Modular and Event-Driven JavaScript
Modular and Event-Driven JavaScriptModular and Event-Driven JavaScript
Modular and Event-Driven JavaScript
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
The Open Web and what it means
The Open Web and what it meansThe Open Web and what it means
The Open Web and what it means
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
jQuery
jQueryjQuery
jQuery
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Recently uploaded (20)

Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

jQuery: Events, Animation, Ajax

  • 2. jQuery Events: .one() // event will be handled only once $("#do").one("click", function () { alert("Done!"); $(this).text("Can't do it :("); }); http://jsfiddle.net/jsfiddlr/CCr5T/
  • 3. jQuery Events: .bind() // one handler for multiple events $("#field").bind("focus blur", function() { $(this).toggleClass("active"); }); http://jsfiddle.net/jsfiddlr/gE2dk/
  • 4. jQuery Events: .bind() // multiple handlers per call $("#field").bind({ click: function () { $("#echo").empty(); }, keyup: function () { $("#echo").text($(this).val()); } }); http://jsfiddle.net/jsfiddlr/U7jF9/
  • 5. jQuery Events: .live() // event will be handled only within context $("p", $("#c2")[0]).live("click", function () { alert("P"); }); // document-wide handling $("p.alt").live("click", function () { alert("P.ALT"); }); http://jsfiddle.net/jsfiddlr/bruQc/
  • 6. jQuery Events: .trigger() // triggers custom event with parameters $("#edit").click (function () { var text = $("#text"); var original = text.text(); text.text("Some another text."); text.trigger("edited", [original, 10]); }); // handles custom event with parameters $("#text").bind("edited", function (event, original, revision) { alert(original + " (rev: " + revision + ")"); }); http://jsfiddle.net/jsfiddlr/vw5E8/
  • 7. jQuery Events: event.result // returns custom result $("h1").click(function () { return 10; }); // uses custom result returned by previous handler $("h1, h2").click(function (event) { alert(event.result); }); http://jsfiddle.net/jsfiddlr/CnFY9/
  • 8. jQuery Events: .remove()/.detach() // removes first para and detaches second // then appends them back to body $("#do").click(function () { // handlers are removed too p1.remove(); // handlers are kept untouched p2.detach(); $("body").append(p1).append(p2); }); p1.click(function () { alert("First"); }); p2.click(function () { alert("Second"); }); http://jsfiddle.net/jsfiddlr/Yq9pM/
  • 9. jQuery Events: namespaces // just another one ordinary handler text.click(function () { alert("?"); }); // namespaced event handler text.bind("click.me", function () { // will be fired on "click" and "click.me" alert("I am!"); }); // multiple namespaced events handler // (not nested, but multiple namespaces) text.bind("click.me.you", function () { // will be fired on "click", "click.me" and/or "click.you" alert("I am! You are too!"); }); // another handler of couple of namespaced events text.bind("mouseover.me mouseout.me",function() { $(this).toggleClass("active"); }); http://jsfiddle.net/jsfiddlr/4L3Fc/
  • 10. jQuery Events: namespaces // triggers non-namespaced event only $("#click").click(function () { text.trigger("click!"); }); // triggers namespaced event $("#click-me").click(function () { text.trigger("click.me"); }); // triggers namespaced event $("#click-you").click(function () { text.trigger("click.you"); }); // unbinds certain event in certain namespace $("#unbind-click-me").click(function () { // profit? delete only certain handlers, not all text.unbind("click.me"); }); // unbinds all events in certain namespace $("#unbind-me").click(function () { // or all namespace members text.unbind(".me"); }); http://jsfiddle.net/jsfiddlr/4L3Fc/
  • 11. jQuery Animation: .stop() // drawback is that if user opens/closes "A" // there will be no effect // until previous animation finished $("#open-a").click(function () { $("#a").animate({ height: "80px" }, 2000, "linear"); }); $("#close-a").click(function () { $("#a").animate({ height: "0" }, 2000, "linear"); }); http://jsfiddle.net/jsfiddlr/48uEK/
  • 12. jQuery Animation: .stop() // here is solution demonstrating .stop() // and certain easing (currently "swing") $("#open-b").click(function () { $("#b").stop(true, true).animate({ height: "80px" }, duration, easing); }); $("#close-b").click(function () { $("#b").stop(true, false).animate({ height: "0" }, duration, easing); }); http://jsfiddle.net/jsfiddlr/48uEK/
  • 13. jQuery Animation: .stop() // another solution (maybe more appropriate), // but example wasn't about this $("#open-a, #close-a").click(function () { var div = $("#a"); if (div.is(":animated")) { return; } div[div.is(":visible") ? "fadeOut" :"fadeIn"](duration); }); http://jsfiddle.net/jsfiddlr/48uEK/
  • 14. jQuery Animation: .queue() // intention: smoothly show element // and then remove it from the DOM $("#b1").click(function () { // element gets removed before // animation finishes $("#a") .fadeIn(duration) .remove(); }); http://jsfiddle.net/jsfiddlr/EXNj9/
  • 15. jQuery Animation: .queue() // solution: use animation queue $("#b2").click(function () { $("#b") .fadeIn(duration) .queue(function(next) { $(this).remove(); // common pattern is to enable execution of // other animations (added after .queue() call) // by calling the next one // (in our example we could omit this) next(); }); http://jsfiddle.net/jsfiddlr/EXNj9/
  • 16. jQuery Ajax: .ajaxStart() $(this) // show spinner at ajax start .ajaxStart(function() { $(this).html( $("#spinner").clone().show()); }) // load content via ajax // when loaded it will replace spinner .load("/echo/html/", { html: "<h1>I've just loaded!</h1>", delay: 3 }); http://jsfiddle.net/jsfiddlr/t38Rx/
  • 17. jQuery Ajax: .ajaxPrefilter() // if URL contains "some" then fake request will be executed $.ajaxPrefilter(function(options, originalOptions, jqXHR) { if (options.url.indexOf("some") >= 0) { options.dataTypes = ["fake"]; } }); http://jsfiddle.net/jsfiddlr/VB9ur/
  • 18. jQuery Ajax: .ajaxTransport() // setting transport for "fake" request $.ajaxTransport("fake", function(options, originalOptions, jqXHR) { // if previous request with certain URL is finished // then process this one if (urls.indexOf(options.url) === -1) { urls += options.url; return { send: function(headers, completeCallback) { setTimeout(function() { urls = urls.replace(options.url, ""); completeCallback(200, "success", { "fake": "Success!" }); }, 5000); }, abort: function () { } }; http://jsfiddle.net/jsfiddlr/VB9ur/
  • 19. jQuery Ajax: .ajaxTransport() // otherwise alert error and send "server error" code } else { alert("Can't call same URL while waiting for response!" ); return { send: function (headers, completeCallback) { completeCallback(500, "error"); }, abort: function () { } }; } http://jsfiddle.net/jsfiddlr/VB9ur/
  • 20. Thanks! Thanks for attention and patience!  constantin.titarenko@binary-studio.com constantin.titarenko@gmail.com October 4, 2011 http://about.me/constantin.titarenko