12
\$\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();
});
asked Mar 7, 2010 at 17:59
\$\endgroup\$

3 Answers 3

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.

answered Mar 7, 2010 at 18:02
\$\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();
});
answered Mar 7, 2010 at 18:02
\$\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');
}
answered Mar 7, 2010 at 18:02
\$\endgroup\$
2
  • \$\begingroup\$ jQuery has this built in :) .toggle(true/false) \$\endgroup\$ Commented Mar 7, 2010 at 18:05
  • \$\begingroup\$ jQuery already has a .toggle function built in. \$\endgroup\$ Commented Mar 7, 2010 at 18:05

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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