Search code examples
jqueryjquery-animatefadeoutslideup

How to change animation name/type in jquery by a string name


This is the concept. what is the possible way to do this
Here my code:

var animationName='slideUp';
if(true){
animationName='fadeOut';
}

$('.className').animationName(200,function(){
     //callback
});

Solution

  • You can use eval() to execute string as javascript expression. In eval() you can use variable as function name.

    var animationName = "slideUp";
    eval("$('div')."+ animationName +"(200, function(){})");
    div {
        width: 50px;
        height: 200px;
        background: green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div></div>