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 Eventsdmethvin
 
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.jsJarod Ferguson
 
An Introduction to Jquery
An Introduction to JqueryAn Introduction to Jquery
An Introduction to JqueryPhil Reither
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Mulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitMulberry: A Mobile App Development Toolkit
Mulberry: A Mobile App Development ToolkitRebecca Murphey
 
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 DevsRebecca Murphey
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceParashuram N
 
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 PauloRobert Nyman
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code OrganizationRebecca Murphey
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuerysergioafp
 
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 AiresRobert 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, CroatiaRobert 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 AiresRobert 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, ChileRobert Nyman
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of TestingMarco Cedaro
 
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, MontevideoRobert 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

Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with WingsRemy Sharp
 
Dispositivos de entrada
Dispositivos de entradaDispositivos de entrada
Dispositivos de entradapatiluki
 
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 pleaseridahprasetio
 
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...ecommerce poland expo
 
Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008Compass Fi Treasury Pp July2008
Compass Fi Treasury Pp July2008ntrung
 
Program book 2013
Program book 2013Program book 2013
Program book 2013otakuthon
 
Jeffrey Sachs
Jeffrey SachsJeffrey Sachs
Jeffrey Sachsrosiem7
 
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, 2015Shawn Yeager
 
Chance challenge change Arise Roby
Chance challenge change   Arise RobyChance challenge change   Arise Roby
Chance challenge change Arise RobyArise Roby
 
Presentations tips
Presentations tipsPresentations tips
Presentations tipsrioulrich
 
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 2014Rhiana Rhiana
 
SE3221 - Playing the Glong Yao
SE3221 - Playing the Glong YaoSE3221 - Playing the Glong Yao
SE3221 - Playing the Glong Yaorememberramc
 
2008111807581919
20081118075819192008111807581919
2008111807581919psy101618
 
Technological applications and innovations
Technological applications and innovationsTechnological applications and innovations
Technological applications and innovationsrbulalakaw
 

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 Secretssmueller_sandsmedia
 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
 
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! - AltranRobert Nyman
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5mennovanslooten
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
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 newRemy Sharp
 
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.5Martin Kleppe
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
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 meansRobert Nyman
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Jack Franklin
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 

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

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 

Recently uploaded (20)

Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 

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