Olivier Pons
Olivier Pons

Reputation: 15796

jQuery: avoid code duplication because of fadeOut()

Here's the problem I've faced many times:

The problem is here: my code looks like this:

function showOnlyElement(myEl)
{
    $('body')
        .children('div:not(.'+myEl+')')
        .fadeOut()
        .promise().done(function() {
            var el=b.children('div.'+myEl);
            if (el.is(':visible')) {
                /* I have to hide it before modifying it */
                el.fadeOut(function() {
                    /* long code (A) modifying the innerHTML of el */
                    el.fadeIn();
                });
            } else {
                /* AGAIN same long code (A) modifying the innerHTML of el */
                el.fadeIn();
            }
        });
}

I just want make it clean so there's not repetition of the same long code (A)

How do you do this (generic way of doing this)?

Upvotes: 3

Views: 98

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382304

Simple generic solution :

$('body')
    .children('div:not(.'+myEl+')')
    .fadeOut()
    .promise().done(function() {
        var el=b.children('div.'+myEl);
        function longCode(){
            /* long code (A) modifying the innerHTML of el */
            el.fadeIn();
        }
        if (el.is(':visible')) {
            el.fadeOut(longCode);
        } else {
            longCode();
        }
    });

Upvotes: 1

Related Questions