hao_maike
hao_maike

Reputation: 3039

jQuery custom toggle function?

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);
};

Upvotes: 2

Views: 4520

Answers (2)

Matt Ball
Matt Ball

Reputation: 359986

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/

Upvotes: 6

Adam Rackis
Adam Rackis

Reputation: 83366

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

Upvotes: 2

Related Questions