Skip to content

Instantly share code, notes, and snippets.

@wolever
Last active January 1, 2016 17:29
Show Gist options
  • Save wolever/8177299 to your computer and use it in GitHub Desktop.
Save wolever/8177299 to your computer and use it in GitHub Desktop.
My preferred pattern for jQuery plugins.
// A simple plugin which zooms the element when it's hovered:
// $("a").hoverzoom();
// Demonstrates my preferred pattern for building jQuery plugins.
$.fn.hoverzoom = function() {
var method = arguments[0] || "init";
var parentArgs = arguments;
this.each(function() {
var args = Array.prototype.slice.call(parentArgs);
args[0] = $(this);
$.fn.hoverzoom[method].apply(null, args);
});
return this;
};
// Note the explicit "self", removing any need to fiddle with "this":
$.fn.hoverzoom = $.extend($.fn.hoverzoom, {
init: function(self) {
self.on("mouseenter mouseleave", function(event) {
self.hoverzoom("toggle", event.type == "mouseenter");
});
},
show: function(self) {
self.stop().animate({
zoom: "200%",
});
self.data("hoverzoom-last", "show");
},
hide: function(self) {
self.stop().animate({
zoom: "100%",
});
self.data("hoverzoom-last", "hide");
},
toggle: function(self, showhide) {
if (showhide === undefined)
showhide = self.data("hoverzoom-last") == "hide";
self.hoverzoom(showhide? "show" : "hide");
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment