SlideShare a Scribd company logo
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.
Ad

More Related Content

What's hot (20)

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
dmethvin
 
DrupalCon jQuery
DrupalCon jQueryDrupalCon jQuery
DrupalCon jQuery
Nathan Smith
 
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
 
An Introduction to Jquery
An Introduction to JqueryAn Introduction to Jquery
An Introduction to Jquery
Phil Reither
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
Rebecca Murphey
 
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
 
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
Rebecca Murphey
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
Parashuram 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 Paulo
Robert Nyman
 
YUI 3
YUI 3YUI 3
YUI 3
Dav Glass
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
Rebecca Murphey
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
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
 
Dojo Confessions
Dojo ConfessionsDojo Confessions
Dojo Confessions
Rebecca Murphey
 
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
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of Testing
Marco Cedaro
 
YUI on the go
YUI on the goYUI on the go
YUI on the go
Christian Heilmann
 
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
 
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
 
An Introduction to Jquery
An Introduction to JqueryAn Introduction to Jquery
An Introduction to Jquery
Phil Reither
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
Rebecca Murphey
 
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
 
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
Rebecca Murphey
 
IndexedDB - Querying and Performance
IndexedDB - Querying and PerformanceIndexedDB - Querying and Performance
IndexedDB - Querying and Performance
Parashuram 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 Paulo
Robert Nyman
 
Functionality Focused Code Organization
Functionality Focused Code OrganizationFunctionality Focused Code Organization
Functionality Focused Code Organization
Rebecca Murphey
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
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
 
The Spirit of Testing
The Spirit of TestingThe Spirit of Testing
The Spirit of Testing
Marco 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, Montevideo
Robert Nyman
 

Viewers also liked (20)

The Power of BIG OER
The Power of BIG OERThe Power of BIG OER
The Power of BIG OER
Patrick McAndrew
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
Remy Sharp
 
Dispositivos de entrada
Dispositivos de entradaDispositivos de entrada
Dispositivos de entrada
patiluki
 
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
ridahprasetio
 
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 July2008
ntrung
 
Memuary Tetrad 1
Memuary Tetrad 1Memuary Tetrad 1
Memuary Tetrad 1
Denis Golikov
 
Program book 2013
Program book 2013Program book 2013
Program book 2013
otakuthon
 
Jeffrey Sachs
Jeffrey SachsJeffrey Sachs
Jeffrey Sachs
rosiem7
 
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
School Vegetable Gardening - Victory Gardens
 
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
Shawn Yeager
 
Chance challenge change Arise Roby
Chance challenge change   Arise RobyChance challenge change   Arise Roby
Chance challenge change Arise Roby
Arise Roby
 
Presentations tips
Presentations tipsPresentations tips
Presentations tips
rioulrich
 
Concumer behavior
Concumer behaviorConcumer behavior
Concumer behavior
shaikirfanbasha
 
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
Rhiana Rhiana
 
SE3221 - Playing the Glong Yao
SE3221 - Playing the Glong YaoSE3221 - Playing the Glong Yao
SE3221 - Playing the Glong Yao
rememberramc
 
2008111807581919
20081118075819192008111807581919
2008111807581919
psy101618
 
Technological applications and innovations
Technological applications and innovationsTechnological applications and innovations
Technological applications and innovations
rbulalakaw
 
Saran makalah kb
Saran makalah kbSaran makalah kb
Saran makalah kb
Operator Warnet Vast Raha
 
Browsers with Wings
Browsers with WingsBrowsers with Wings
Browsers with Wings
Remy Sharp
 
Dispositivos de entrada
Dispositivos de entradaDispositivos de entrada
Dispositivos de entrada
patiluki
 
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
ridahprasetio
 
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 July2008
ntrung
 
Program book 2013
Program book 2013Program book 2013
Program book 2013
otakuthon
 
Jeffrey Sachs
Jeffrey SachsJeffrey Sachs
Jeffrey Sachs
rosiem7
 
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
Shawn Yeager
 
Chance challenge change Arise Roby
Chance challenge change   Arise RobyChance challenge change   Arise Roby
Chance challenge change Arise Roby
Arise Roby
 
Presentations tips
Presentations tipsPresentations tips
Presentations tips
rioulrich
 
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
Rhiana Rhiana
 
SE3221 - Playing the Glong Yao
SE3221 - Playing the Glong YaoSE3221 - Playing the Glong Yao
SE3221 - Playing the Glong Yao
rememberramc
 
2008111807581919
20081118075819192008111807581919
2008111807581919
psy101618
 
Technological applications and innovations
Technological applications and innovationsTechnological applications and innovations
Technological applications and innovations
rbulalakaw
 
Ad

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

jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
Bastian Feder
 
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
 
Modular and Event-Driven JavaScript
Modular and Event-Driven JavaScriptModular and Event-Driven JavaScript
Modular and Event-Driven JavaScript
Eduardo Shiota Yasuda
 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Michael Girouard
 
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
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
mennovanslooten
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
Bastian Feder
 
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
 
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
Martin Kleppe
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew 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 means
Robert Nyman
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
jQuery
jQueryjQuery
jQuery
Ivano Malavolta
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9
Jack Franklin
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
Frank de Jonge
 
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
 
amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5amsterdamjs - jQuery 1.5
amsterdamjs - jQuery 1.5
mennovanslooten
 
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
 
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
Martin Kleppe
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew 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 means
Robert Nyman
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9Introduction to jQuery - Barcamp London 9
Introduction to jQuery - Barcamp London 9
Jack Franklin
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Ad

Recently uploaded (20)

apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptxLecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Arshad Shaikh
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
Computer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issuesComputer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issues
Abhijit Bodhe
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE  BY sweety Tamanna Mahapatra MSc PediatricAPGAR SCORE  BY sweety Tamanna Mahapatra MSc Pediatric
APGAR SCORE BY sweety Tamanna Mahapatra MSc Pediatric
SweetytamannaMohapat
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Link your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRMLink your Lead Opportunities into Spreadsheet using odoo CRM
Link your Lead Opportunities into Spreadsheet using odoo CRM
Celine George
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18How to Manage Purchase Alternatives in Odoo 18
How to Manage Purchase Alternatives in Odoo 18
Celine George
 
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptxLecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Lecture 2 CLASSIFICATION OF PHYLUM ARTHROPODA UPTO CLASSES & POSITION OF_1.pptx
Arshad Shaikh
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
Form View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo SlidesForm View Attributes in Odoo 18 - Odoo Slides
Form View Attributes in Odoo 18 - Odoo Slides
Celine George
 
dynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south Indiadynastic art of the Pallava dynasty south India
dynastic art of the Pallava dynasty south India
PrachiSontakke5
 
How to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo SlidesHow to Add Customer Note in Odoo 18 POS - Odoo Slides
How to Add Customer Note in Odoo 18 POS - Odoo Slides
Celine George
 
Grade 3 - English - Printable Worksheet (PDF Format)
Grade 3 - English - Printable Worksheet  (PDF Format)Grade 3 - English - Printable Worksheet  (PDF Format)
Grade 3 - English - Printable Worksheet (PDF Format)
Sritoma Majumder
 
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
Drive Supporter Growth from Awareness to Advocacy with TechSoup Marketing Ser...
TechSoup
 
Computer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issuesComputer crime and Legal issues Computer crime and Legal issues
Computer crime and Legal issues Computer crime and Legal issues
Abhijit Bodhe
 
Rock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian HistoryRock Art As a Source of Ancient Indian History
Rock Art As a Source of Ancient Indian History
Virag Sontakke
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 SalesHow to Manage Upselling in Odoo 18 Sales
How to Manage Upselling in Odoo 18 Sales
Celine George
 
How to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo SlidesHow to Create Kanban View in Odoo 18 - Odoo Slides
How to Create Kanban View in Odoo 18 - Odoo Slides
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 

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