KEMBAR78
jQuery: Events, Animation, Ajax | PDF
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.

jQuery: Events, Animation, Ajax

  • 1.
  • 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
  • 21.