Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>jQuery has two methods called <code>.toggle()</code>. The <a href="http://api.jquery.com/toggle-event/" rel="noreferrer">other one <em><sup>[docs]</sup></em></a> does exactly what you want for click events.</p> <p><strong>Note:</strong> It seems that at least since <strong>jQuery 1.7</strong>, this version of <code>.toggle</code> is <strong>deprecated</strong>, probably for exactly that reason, namely that two versions exist. Using <code>.toggle</code> to change the visibility of elements is just a more common usage. The method was <strong>removed in jQuery 1.9</strong>.</p> <p>Below is an example of how one could implement the same functionality as a plugin (but probably exposes the same problems as the built-in version (see the last paragraph in the documentation)).</p> <hr> <pre><code>(function($) { $.fn.clickToggle = function(func1, func2) { var funcs = [func1, func2]; this.data('toggleclicked', 0); this.click(function() { var data = $(this).data(); var tc = data.toggleclicked; $.proxy(funcs[tc], this)(); data.toggleclicked = (tc + 1) % 2; }); return this; }; }(jQuery)); </code></pre> <p><a href="http://jsfiddle.net/npwAz/1/" rel="noreferrer"><strong>DEMO</strong></a></p> <p><em>(Disclaimer: I don't say this is the best implementation! I bet it can be improved in terms of performance)</em></p> <p>And then call it with:</p> <pre><code>$('#test').clickToggle(function() { $(this).animate({ width: "260px" }, 1500); }, function() { $(this).animate({ width: "30px" }, 1500); }); </code></pre> <p><strong>Update 2:</strong></p> <p>In the meantime, I created a proper plugin for this. It accepts an arbitrary number of functions and can be used for any event. <a href="https://github.com/fkling/jQuery-Function-Toggle-Plugin" rel="noreferrer">It can be found on GitHub</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload