Q:

How can i optimize my Jquery code?

I've created some JavaScript using Jquery, for the page animation :
I trying to optimize it since i repeat the same thing for subtab1, subtab2, subtab3.
The same function is executed for all of them, and the only thing is changes is variable i iterating on?
Any suggestion?
<script type="text/javascript">
  $(document).ready(function () {

    var $defensivo = $('#defensivoimg');
    var $equilibrado = $('#equilibradoimg');
    var $activo = $('#activoimg');

    var $defensivoSubTab = $('#subtab1');
    var $equilibradoSubTab = $('#subtab2');
    var $activoSubTab = $('#subtab3');

    var $fundosdiponiveis = $('#fundosdiponiveis');
    var $fundosdiponiveisTab = $('#tabs1');

    $defensivo.live('click', function () {
      $fundosdiponiveis.removeClass("subshow show").addClass("hide");
      $defensivoSubTab.removeClass("hide");
      $defensivoSubTab.show();
    });

    $equilibrado.live('click', function () {
      $fundosdiponiveis.removeClass("subshow show").addClass("hide");
      $equilibradoSubTab.removeClass("hide");
      $equilibradoSubTab.show();
    });

    $activo.live('click', function () {
      $fundosdiponiveis.removeClass("subshow show").addClass("hide");
      $activoSubTab.removeClass("hide");
      $activoSubTab.show();
    });
  });
</script>

For a while:
var $fundosdiponiveis = $('#fundosdiponiveis');

This is my default div.
var $defensivoSubTab = $('#subtab1');
var $equilibradoSubTab = $('#subtab2');
var $activoSubTab = $('#subtab3');

That divs apears when i clicking on one of the following tabs:
var $defensivo = $('#defensivoimg');
var $equilibrado = $('#equilibradoimg');
var $activo = $('#activoimg');

And that button hides and changes style"display" to none, on click, of my three #subtab's
var $fundosdiponiveisTab = $('#tabs1');

Any suggestion?

A:

You could write a function that returns the proper function:
function createShowTabFunc(tab) {
  return function () {
    $fundosdiponiveis.removeClass("subshow show").addClass("hide");
    tab.removeClass("hide");
    tab.show();
  }
}

Then assign your click handlers:
$defensivo.live('click', createShowTabFunc($defensivoSubTab));
$equilibrado.live('click', createShowTabFunc($equilibradoSubTab));
$activo.live('click', createShowTabFunc($activoSubTab));

