Alternar dinamicamente os elementos da página sem escrever código repetitivo

Em muitos projetos da web, preciso alternar o estado de um elemento clicando em outro. Em vez de escrever manipuladores para cada um desses gatilhos, prefiro usar este trecho de código reutilizável que me permite anexar esse comportamento usando o atributo de dados HTML.

Aproveitar!

/**
* Toggle everything!

*

* Options:

* ----------------------

* data-toggle="<selector>" The element that should be toggled.

* data-toggle-class="<classname>" [optional] The classname that should be toggled on the target. If empty, display will be toggled

* data-toggle-alt-html="<content>" [optional] Alternate content that should be displayed in the toggling element

* data-toggle-duration="<duration>" [optional] Duration of the effect. Instant if empty.

*

* Example:

* ----------------------

* <a href="#" data-toggle="#some-form" data-toggle-alt-html="Hide form">Show form</a>

* <form action="" id="some-form"><button type="submit">Submit it!</button></form>

*

*/


$
('[data-toggle]').click(function() {
var $this = $(this);
var ref = $(this).data('toggle');
if ($(this).data('toggle-alt-html')) {
if ($(this).data('toggle-alt-html') == $(this).html()) {
$
(this).html($(this).data('original-html'));
} else {
$
(this).data('original-html', $(this).html());
$
(this).html($(this).data('toggle-alt-html'));
}
}

var duration = $(this).data('toggle-duration') || 0;

if ($(this).data('toggle-class')) {
$
(ref).toggleClass($(this).data('toggle-class'));
} else {
$
(ref).toggle(duration);
}

$
(this).toggleClass('active');
// trigger a custom event to allow for additional event handlers
$
(this).trigger('afterToggle');

// generally, you'd want anchors to do nothing when toggling behavior
if ($(this).is('a')) {
return false;
}
});