2

I'm trying to make a custom jQuery toggle function. Right now, I have 2 separate functions, lightsOn and lightsOff. How can I combine these functions to make them toggle (so I can just link to one function)?

function lightsOn(){
 $('#dim').fadeOut(500,function() {
   $("#dim").remove();
 });
};

function lightsOff(){
 $('body').append('<div id="dim"></div>');
 $('#dim').fadeIn(250);
};

2 Answers 2

6
function toggleLights()
{
    var $dim = $('#dim');
    if ($dim.length)
    {
        $dim.fadeOut(500, function ()
        {
            $dim.remove();
        });
    }
    else
    {
        $dim = $('<div/>', {id: 'dim'});
        $('body').append($dim);
        $dim.fadeIn(250);
    }
}

Demo: http://jsfiddle.net/mattball/hxL8s/

Sign up to request clarification or add additional context in comments.

Comments

2
function toggleLights(){
    if ($("body").has("#dim")) {
        $('#dim').fadeOut(500, function() {
           $("#dim").remove();
        });
    } else {
        $('body').append('<div id="dim"></div>');
        $('#dim').fadeIn(250);
   }
}

3 Comments

Meh, you really don't need to keep re-querying the DOM for #dim.
Hmm.. thanks for the help, however it doesn't work for me. (The one from MДΓΓ БДLL does, however.)
@MДΓΓБДLL - true - I doubt it would ever matter - especially since you're querying by id. Besides, to optimize it I'd basically be copying your answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.