I’m trying to retrieve parameters as a string and directly feed them to jQuery’s animate function like so:
my html:
<img src="myImage.png" rel="{top:'20px',left:'1000px'},500|{top:'20px',left:'10px'},500" class="slide-content" />
my jQuery code:
var $elem = $('.slide-content');
var settings = $elem.attr('rel').split('|');
$elem.animate(settings[1]);
This does not work. If I put the setting manually it works:
$elem.animate({top:'20px',left:'1000px'},500);
Is there a simple way of making it work? Or do I have to parse the string and build up a settings object?
Any pointers would be appreciated, thanx!
Edit after Jon’s anwser:
Turns out you have to parse correctly formed JSON and so I updated the code like so
HTML:
<img src="myImage.png" rel='{"anim":{"top":"20px","left":"1000px"},"speed":"500"}|{"anim":{"top":"20px","left":"20px"},"speed":"500"}' class="slide-content" />
Notice how the html rel attribute is wrapped in single quotes instead of double quotes. This is because JSON elements need to be wrapped in double quotes.
jQuery part:
var $elem = $('.slide-content');
var settings = $elem.attr('rel').split('|');
var animIn = $.parseJSON(settings[1]);
var animOut = $.parseJSON(settings[0]);
$elem.animate(animIn.anim, animIn.speed).delay(2000).animate(animOut.anim, animIn.speed);
Just to clear up the why behind the question:
-
this will serve as basis for a slider plugin in which each inner part will be animated independently and must be easy for the user to setup within the HTML element itself
-
must run on a website using XHTML
Anyhow thank you for the quick responses and helpfull indications 🙂
You need to pass an object, not a string. You already have the JSON representation of an object, so you just need to make an object out of it. Do that with
JSON.parse, which all modern browsers support.Update: I just paid more attention and realized that you have tried to also shoehorn in the animation duration in there, which doesn’t help (it makes things more complicated). You should consider changing the HTML to something like:
which would then allow you to do:
As an aside: commandeering the
relattribute like that is probably not the best of ideas. If you want to attach arbitrary data to an element like that, you can use HTML 5 data attributes: