0

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?

0

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

Comments

1

Have a common class attribute to all the tab's and you just need to write $('.class').click() and in this get the id of the corresponding tab and according to the id fetched by attr function, you can have an if else to define your variables inside the if else and execute your code block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.