Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Destroy / Cleanup Pattern</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style>#box{padding:10px;border:1px solid #ccc;width:260px}</style> </head> <body> <div id="box">Plugin target</div> <button id="init">Init</button> <button id="destroy">Destroy</button> <script> (function($){ $.fn.clickable = function(cmd){ if(cmd === 'destroy'){ return this.each(function(){ $(this).off('.clickable').removeData('clickable-init').css('background',''); }); } return this.each(function(){ var $el = $(this); if($el.data('clickable-init')) return; $el.data('clickable-init', true); $el.on('click.clickable', function(){ $el.css('background','#ffe082'); }); }); }; })(jQuery); $("#init").on("click", function(){ $("#box").clickable(); }); $("#destroy").on("click", function(){ $("#box").clickable('destroy'); }); </script> </body> </html>
Output