Last active
January 1, 2016 17:29
-
-
Save wolever/8177299 to your computer and use it in GitHub Desktop.
My preferred pattern for jQuery plugins.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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