0

Lets say I have the following function

function slide(element, direction, hide){
    if (direction == "left") {
        $(element).animate({
            "left": 500,
        }, 500, function(){
            if(hide) {
                $(element).css("display", "none");
            }
        });
    } else {
        $(element).animate({
            "right": 500,
        }, 500, function(){
            if(hide) {
                $(element).css("display", "none");
            }
        });
    }
}

which works great by itself. But I would like to eliminate the If else term to get something like this

function slide(element, direction, hide){
    $(element).animate({
        direction : 500,
    }, 500, function(){
        if(hide) {
            $(element).css("display", "none");
        }
    });
}

Which doesnt work at all... Is there any way to control left/right by variable in animate function?

Snackaholic
  • 590
  • 7
  • 27

1 Answers1

1

Create a object yourself with direction and then use it in animate function like following.

function slide(element, direction, hide) {
    var obj = {};
    obj[direction] = 500;

    $(element).animate(obj, 500, function () {
        if (hide) {
            $(element).css("display", "none");
        }
    });
}
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55