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

Lots of click handlers that hide one element and show another

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
showclickhandlerslotsonethatelementanotherandhide

Problem

I've a lot of code blocks that hide/show some block.

$('#Back').on('click', function () {
    $('#FormRow').hide();
    $('#TableRow').show();
});

$('#AddLanguageShow').on('click', function () {
    $('#FormRow').show();
    $("#TableRow").hide();
});

$('table').on('click', 'button.edit', function (evt) {
    $('#FormRow').show();
    $('#TableRow').hide();
    languageManager.load(getRowId($(this)));
});


Is it possible to split logic of changing blocks visibility ?

Solution

Extract the duplicated code to a function:

function showOneHideOther(elToShow, elToHide) {
    $(elToShow).show();
    $(elToHide).hide();
}


You can reuse the function anyplace now:

$('#Back').on('click', function() {
    showOneHideOther('#TableRow', '#FormRow')
});
$('#AddLanguageShow').on('click', function() {
    showOneHideOther('#FormRow', '#TableRow')
});

$('table').on('click', 'button.edit', function (evt) {
    showOneHideOther('#FormRow', '#TableRow')
    languageManager.load(getRowId($(this)));
});

Code Snippets

function showOneHideOther(elToShow, elToHide) {
    $(elToShow).show();
    $(elToHide).hide();
}
$('#Back').on('click', function() {
    showOneHideOther('#TableRow', '#FormRow')
});
$('#AddLanguageShow').on('click', function() {
    showOneHideOther('#FormRow', '#TableRow')
});

$('table').on('click', 'button.edit', function (evt) {
    showOneHideOther('#FormRow', '#TableRow')
    languageManager.load(getRowId($(this)));
});

Context

StackExchange Code Review Q#49865, answer score: 3

Revisions (0)

No revisions yet.