Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>State with $.data()</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style>#counter{padding:10px;border:1px solid #ccc;width:200px;display:inline-block}</style> </head> <body> <div id="counter">0</div> <button id="inc">Increment</button> <script> (function($){ $.fn.counter = function(){ return this.each(function(){ var $el = $(this); $el.data('count', 0); $el.text(0); }); }; $.fn.counterInc = function(step){ step = step || 1; return this.each(function(){ var $el = $(this); var v = $el.data('count') || 0; v += step; $el.data('count', v).text(v); }); }; })(jQuery); $("#counter").counter(); $("#inc").on("click", function(){ $("#counter").counterInc(); }); </script> </body> </html>
Output