Search code examples
javascriptjqueryconditional-statementschaining

Can I assign function based on the condition in jquery?


I have two similar function as below;

For last element function;

function last () {
    var $this = $(this);

    $this.animate({
        left:'-1200',
        opacity:0
    },500, function(){
        $this
        .addClass('hide')
        .next()
        .removeClass('hide').animate({
            left:'0',
            opacity:1
        },500)
    });
}

For first element function;

function first () {
    var $this = $(this);

    $this.animate({
        left:'1200',
        opacity:0
    },500, function(){
        $this
        .addClass('hide')
        .prev()
        .removeClass('hide').animate({
            left:'0',
            opacity:1
        },500)
    });
}

they are similar and I want to combine them as one function, as below;

function steps (pos) { /* -- Dif-1 -- */
    var $this = $(this);

    $this.animate({
        left:pos==='next'&& '-'+'1200', /* -- Dif-2 -- */
        opacity:0
    },500, function(){
        $this
        .addClass('hide')
            pos==='next' ? next() : prev()  /* -- Dif-3 -- */
        .removeClass('hide').animate({
            left:'0',
            opacity:1
        },500)
    });    
}

I want to determine function next() or prev() according to pos variable (pos==='next' ? next() : prev() ). How can I do this?


Solution

  • The difference in your left property can be done using a simple ternary operator:

    left: pos==='next' ? -1200 : 1200
    

    And you can continue chaining your methods if you use bracket notation to call prev() or next():

    $this.addClass('hide')
    [pos==='next' ? "next" : "prev"]()
    .removeClass('hide').animate({
    

    Or, assuming pos will always be either next or prev, simply use [pos]():

    function steps (pos) {
        var $this = $(this);
    
        $this.animate({
            left:pos==='next' ? -1200 : 1200,
            opacity:0
        },500, function(){
            $this
            .addClass('hide')[pos]()
            .removeClass('hide').animate({
                left:'0',
                opacity:1
            },500)
        });    
    }