Source: Extending an existing jQuery function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
(function($) { // maintain a reference to the existing function var oldcss = $.fn.css; // ...before overwriting the jQuery extension point $.fn.css = function() { // original behavior - use function.apply to preserve context var ret = oldcss.apply(this, arguments); // stuff I will be extending // that doesn't affect/change // the way .css() works // preserve return value (probably the jQuery object...) return ret; }; })(jQuery); |
Aller plus loin avec un callback
Source: Coderbits – Extending jQuery with onShow and onHide events.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<!-- Include latest jquery first! --> <script> //Extending show-function example at http://stackoverflow.com/questions/5007279/extending-an-existing-jquery-function (function ($) { //Extend show() so that it trigger our event when called var show = $.fn.show; $.fn.show = function () { var ret = show.apply(this, arguments); //Read comments about these part at the stackoverflow linked above $(this).trigger("onShow"); //Trigger our new onShow event return ret; //Return object so that it can propagate }; //Extend hide() var hide = $.fn.hide; $.fn.hide = function () { var ret = hide.apply(this, arguments); //Read comments about these part at the stackoverflow linked above $(this).trigger("onHide"); //Trigger our new onShow event return ret; //Return object so that it can propagate }; //Define new event functions $.fn.onShow = function (callback) { if (callback != null) { $(this).on("onShow", function () { callback(); //Trigger callback }); } else { $(this).trigger("onShow"); //If no callback exist we trigger the event } return this; }; $.fn.onHide = function (callback) { if (callback != null) { $(this).on("onHide", function () { callback(); //Trigger callback }); } else { $(this).trigger("onHide"); //If no callback exist we trigger the event } return this; }; })(jQuery); //All the above code could be saved in an external .js file which is much easier to include //Testing time! $(function () { //DOM ready //Define what happens if our element is shown $("#testingElement").onShow(function () { alert("Hello!"); }); //Define what happens if our element is hidden $("#testingElement").onHide(function () { alert("Goodbye!"); }); //Button event $("button").click(function () { $("#testingElement").toggle(); }); }); </script> <p id="testingElement" style="display:none;">Showing</p> <button>Show</button> |