patternjavascriptModerate
More elegant way to show | hide in jQuery
Viewed 0 times
showmorewayjqueryeleganthide
Problem
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();
});Solution
You can shorten it down:
Likely, you can shorten it to:
Just depends how the initial state of things are.
$('#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.
Code Snippets
$('#shw_test').click(function() {
$('#hde_test, #shw_test').toggle();
$('.class1').show();
});
$('#hde_test').click(function() {
$('#hde_test, #shw_test').toggle();
$('.class1').hide();
});$('#shw_test, #hde_test').click(function() {
$('#hde_test, #shw_test, .class1').toggle();
});Context
StackExchange Code Review Q#11094, answer score: 16
Revisions (0)
No revisions yet.