HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

More elegant way to show | hide in jQuery

Submitted by: @import:stackexchange-codereview··
0
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:

$('#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.