Reputation: 3039
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
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
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