PyRoss
PyRoss

Reputation: 129

jQuery: passing arguments into the animate method as properties

My problem with jQuery is that the animation doesn't work when I use an arguement dir, but when I flat out type left or right (exactly the same values that dir passes) it seems fine.

function update(dir) {
    $('#label').animate({
        dir: '200px'
    }, 'slow');
}
$('#goLeft').click(function() {
    update('left');
});

Upvotes: 1

Views: 35

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240928

You could use bracket notation in order to pass a variable as a property.

In this case, you would use [dir]:

function update(dir) {
    $('#label').animate({
        [dir]: '200px'
    }, 'slow');
}

Basic example:

function update(dir) {
    $('#animate').animate({
        [dir]: '100px'
    }, 'slow');
}
$('#go-left').click(function() {
    update('left');
});
$('#go-down').click(function() {
    update('top');
});
#animate { position: relative; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="go-left">Go left</button>
<button id="go-down">Go down</button>
<div id="animate">Animate me</div>

Upvotes: 4

Related Questions