0

I'm new in stack, so be patient with me, please. I have a simple function with parameters and I'm using Jquery:

function AnimateValues(a, b, c, d){
  return $(a).stop().animate({b : c}, d);
}

now, I'd like to call it when needed eg:

AnimateValues('#div1', 'opacity', 1, 500);
AnimateValues('#div2', 'opacity', 0, 500);
AnimateValues('#div3', 'top', 20, 500);
...

but it seems only the last one is executed. Helps will be appreciate.

pitinca
  • 143
  • 8
  • Are you calling the function in a loop, or actually three times in a row as shown above – Mobius Oct 11 '17 at 15:08
  • Can you please post the HTML code from where you are calling the function. – Kamal Chanda Oct 11 '17 at 15:09
  • 5
    `only the last one is executed` does not make sense, because your code should not work for any of them in the way you expect, because `{b : c}` would not use the value of the parameter `b` as key for the object but the name `b` itself. So it would never animate `top` or `opactiy`. – t.niese Oct 11 '17 at 15:09
  • I supposed to use a loop but no, I need to call it as shown 'cause I don't know in advance how many times I need to call it. – pitinca Oct 11 '17 at 15:12
  • 1
    Possible duplicate of [dynamic keys for object literals in Javascript](https://stackoverflow.com/questions/6500573/dynamic-keys-for-object-literals-in-javascript) – Makyen Oct 11 '17 at 15:19

2 Answers2

1

You need to wrap b parameter in [] otherwise its just string key.

function AnimateValues(a, b, c, d){
  return $(a).stop().animate({[b] : c}, d);
}

AnimateValues('#div1', 'opacity', 1, 500);
AnimateValues('#div2', 'opacity', 0, 500);
AnimateValues('#div3', 'top', 20, 500);
div {
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">Div1</div>
<div id="div2">Div2</div>
<div id="div3">Div3</div>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • 1
    Another time, please use the dup-hammer granted by having a gold badge in JavaScript to *close* duplicate question instead of providing answers to them. – Makyen Oct 11 '17 at 15:32
-1

This is not really an answer to your question because, only the last one is executed does not make sense.

Your code should not work for any of them in the way you expect, because {b : c} would not use the value of the parameter b as key for the object but the name b itself. So it would never animate top or opactiy

If you can use ES6 features then you could write [b] instead of b which would use the value ob b as key.

function AnimateValues(a, b, c, d){
  return $(a).stop().animate({[b] : c}, d);
}

Or

function AnimateValues(a, b, c, d){
  var params = {};
  params[b] = c;
  return $(a).stop().animate(params, d);
}

But as I said, this would not explain your only the last one is executed.

t.niese
  • 39,256
  • 9
  • 74
  • 101