views:

444

answers:

2
function SlideObject(Side) {
    $("#div").animate({
        margin+Side: "-1000px",
        opacity: "hide"
    }, 1000);
}

I would like to pass the value for "Side" into the name of property identifier (margin) for the animate function.

I am aware that "margin+Side" is not valid it is just there as a place holder. For example if I were to specify the property name manually it could be "marginLeft" to name one example. I would like to supply "Left", "Right", "Top" or "Bottom" as the parameter for the SlideObject function.

I'm having trouble do this and an example would be wonderful.

Thanks

+3  A: 

Firstly, don't use eval() to do this. There's no need and that opens up your site to vulnerabilities if you are in any way using user input as part of that (directly or indirectly). The right way to do this is:

<div id="div">This is a test</div>

with CSS:

#div { padding: 15px; background: yellow; }

and Javascript:

function slideObject(side) {
  var anim = {opacity: 0};
  anim["margin" + side] = "-1000px";
  $("#div").animate(anim, 1000);
}

$(function() {
  slideObject("Left");
});

You'll note that the opacity value is changed to 0. hide is not a valid value for opacity.

Basically you create the anonymous object and then assign a dynamic property using [].

cletus
For some reason this does not work...
fuzzywuzzy
My intension is not to be controversial, but how that might be a vulnerability? I mean, it runs in **MY** browser.
metrobalderas
Cross-site scripting (XSS), meaning someone may be able to inject JS so that it runs on your site and then has access to stuff it otherwise wouldn't.
cletus
@cletus, an example might help the OP. i.e. `SlideObject('left')` would fail, but `SlideObject('Left')` and `SlideObject('-left')` would work. Why did you switch from straight object notation? It was cleaner before IMO.
Doug Neiner
This still wont work im lost as to why...
fuzzywuzzy
@Doug: I tried the straight object notation and it didn't work. The above worked fine with an example I did using padding.
cletus
could you post that entire example because it doesn't work for me, why wouldn't straight object notation work anyway? Not being able to do this degrades the value of having a framework.
fuzzywuzzy
I have zero idea why but this wont work either.
fuzzywuzzy
A: 

can someone add a little more info to this? What does this do?

var anim = {opacity: 0}; anim["margin" + side] = "-1000px";

the anim = {...} makes it an object, right? does the 2nd line append the "margin"+side to that object? so now we have anim.opacity and anim.marginSide?

Thanks!

Nevermind! :)

I figured it out. Here's how I implemented the above:

function slideObject(id, dir, val, oVal) {
  var elem = {};
  elem[dir] = val + "px";

  id.animate(elem, 100, function(){
    elem[dir] = oVal + "px";
    id.animate(elem, 200);
  });
}

slideObject($("#div"), "right", 45, 50);
chris