Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Plugin Events & Namespaces</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">Click to toggle</div> <pre id="log"></pre> <script> (function($){ $.fn.toggler = function(){ return this.each(function(){ var $el = $(this); $el.on('click.toggler', function(){ $el.toggleClass('on'); $el.trigger('toggler:change', [$el.hasClass('on')]); }); }); }; })(jQuery); $("#box").toggler().on("toggler:change", function(e, isOn){ $("#log").append("state=" + isOn + "\n"); }); </script> </body> </html>
Output