Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Plugin Methods & Chaining</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style>#box{padding:10px;border:1px solid #ccc;width:260px;position:relative;height:80px}</style> </head> <body> <div id="box">Box</div> <button id="run">Animate</button> <script> (function($){ function Animator($el){ this.$el = $el; } Animator.prototype.move = function(px){ this.$el.animate({left: "+=" + px}, 200); return this; }; Animator.prototype.flash = function(){ var $e=this.$el; return $e.fadeOut(100).fadeIn(100), this; }; $.fn.animator = function(){ return this.each(function(){ var inst = new Animator($(this).css('position','relative')); $(this).data('animator', inst); }); }; $.fn.animatorMove = function(px){ return this.each(function(){ $(this).data('animator').move(px); }); }; $.fn.animatorFlash = function(){ return this.each(function(){ $(this).data('animator').flash(); }); }; })(jQuery); $("#box").animator(); $("#run").on("click", function(){ $("#box").animatorMove(40).animatorFlash().animatorMove(-20); }); </script> </body> </html>
Output