11
\$\begingroup\$

What is the best way to optimize this jQuery code?

$('#hde_test').hide();

$('#shw_test').click(function() {
    $('#shw_test').hide();
    $('#hde_test').show();
    $('.class1').show();
});
$('#hde_test').click(function() { 
    $('#shw_test').show();
    $('#hde_test').hide();
    $('.class1').hide();
});
\$\endgroup\$
16
\$\begingroup\$

You can shorten it down:

$('#shw_test').click(function() {
    $('#hde_test, #shw_test').toggle();
    $('.class1').show();
});
$('#hde_test').click(function() { 
    $('#hde_test, #shw_test').toggle();
    $('.class1').hide();
});

Likely, you can shorten it to:

$('#shw_test, #hde_test').click(function() {
    $('#hde_test, #shw_test, .class1').toggle();
});

Just depends how the initial state of things are.

\$\endgroup\$
0
5
\$\begingroup\$

You can use the .toggle() method or .toggleClass() method to toggle the objects visibility. That would let you do something like:

$('#show_toggle').click(function() {
    $('.class1').toggle();
});
\$\endgroup\$
3
\$\begingroup\$

You could refactor that into a "toggle" function:

function toggle(show, hide)
{
   $(show).show();
   $(hide).hide();
}

function doStuff(){
  //this will show shw_test and hide hde_test
  toggle('#shw_test', '#hde_test');

}
\$\endgroup\$
2
  • \$\begingroup\$ jQuery has this built in :) .toggle(true/false) \$\endgroup\$ Mar 7 '10 at 18:05
  • \$\begingroup\$ jQuery already has a .toggle function built in. \$\endgroup\$ Mar 7 '10 at 18:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy