Walter Wilson
Walter Wilson

Reputation: 11

JavaScript string and object in array

I'm trying to animate some divs from an initial location to other locations.

For this, I am adapting the code from this fiddle:

http://jsfiddle.net/c6UEm/27/

The code I have is:

function animate(list, lft, top, callback) {

alert('list: '+list);

if (list.length === 0) {
    callback();
    return;
}
$el = list.shift();         // div ids
var lll = lft.shift();  // new value for left of this div (from lft array)
var ttt = top.shift();  // new value for top of this div (from top array)
$el.animate({"left": +lll+'px', "top": +ttt+'px'}, 1000, function () {
    animate(list, lft, top, callback);
});
}

If I hard-code 'list' (div ids) as follows;

    $('#TDA0mv'),$('#TDA1mv'),$('#TDA2mv'),$('#TDA3mv'),$('#TDA4mv'),$('#TDA5mv'),$('#TDA6mv'),$('#TDA7mv'),$('#TDA8mv')

the alert above produces this;

list: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

which works as required.

If I retrieve the ids from a hidden field and build an array (or even a string that is then split) I have this;

       $('#TDA0mv'),$('#TDA1mv'),$('#TDA2mv'),$('#TDA3mv'),$('#TDA4mv'),$('#TDA5mv'),$('#TDA6mv'),$('#TDA7mv'),$('#TDA8mv')

which at the above alert call is:

list:$('#TDA0mv'),$('#TDA1mv'),$('#TDA2mv'),$('#TDA3mv'),$('#TDA4mv'),$('#TDA5mv'),$('#TDA6mv'),$('#TDA7mv'),$('#TDA8mv')

Naturally, this doesn't work.

Has anyone any ideas as to why seemingly identical data objects are so different? I suspect this maybe a JSON-type thing, as a number of 'similar' queries are answered thus. However, having tried a couple of things in this direction I still seem to end up with strings and not 'objects'.

Upvotes: 1

Views: 188

Answers (1)

sdespont
sdespont

Reputation: 14025

You are not explaining how you pass the ids, but you can't just use <input type="hidden" value="$('#id')" /> because it will be interpreted as text and not as JQuery object.

You could do like this : http://jsfiddle.net/c6UEm/28/

<body>
  <div id="container">
    <div id="one" class="box"></div>
    <div id="two" class="box"></div>
    <div id="three" class="box"></div>
  </div>
    <!-- Create an input field-->
    <input type="hidden" id="list" value=""/>
</body>

$(document).ready(function () {
    //Assign id values
    $('#list').val('one,two,three');

    //Pass the list to your function
    animate($('#list').val().split(','), finished);
});

function finished() {
    $('body').append('Finished');
}

function animate(list, callback) {
    if (list.length === 0) {
        callback();
        return;
    }

    //Use id to use with JQuery
    $el = $('#' + list.shift());
    $el.animate({left: '+=200',top: '-=10'}, 1000, function () {
        animate(list, callback);
    });
}

Upvotes: 1

Related Questions