\$\begingroup\$
\$\endgroup\$
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
JohnJohn
3 Answers 3
\$\begingroup\$
\$\endgroup\$
0
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
\$\begingroup\$
\$\endgroup\$
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
\$\begingroup\$
\$\endgroup\$
2
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
-
\$\begingroup\$ jQuery has this built in :)
.toggle(true/false)
\$\endgroup\$Nick Craver– Nick Craver2010年03月07日 18:05:05 +00:00Commented Mar 7, 2010 at 18:05 -
\$\begingroup\$ jQuery already has a .toggle function built in. \$\endgroup\$Benjamin Manns– Benjamin Manns2010年03月07日 18:05:32 +00:00Commented Mar 7, 2010 at 18:05
default