user3871
user3871

Reputation: 12708

move DOM element position dynamically

I'm generating spans dynamically and placing their location as such:

        $('#myObstacles').append("<span id=\"" +  test + randX + "\">" + items[randObj] + "</span>");
        document.getElementById("test"+randX).style.position="absolute";
        document.getElementById("test"+randX).style.left=randX;
        document.getElementById("test"+randX).style.top=randY;

Then I have setInterval() function that should move these DOM spans every so often by calling moveSpans():

    function moveSpans() {
        $("#myObstacles span").each(function (index, val) {
            val.style.top-=10;
        });
    }

For some reason, the appended DOM spans to #myObstacles don't change position.

Why is this?

Upvotes: 0

Views: 1828

Answers (3)

Ivan Guardado
Ivan Guardado

Reputation: 527

Have you tried this?

function moveSpans() {
    $("#myObstacles span").each(function (index, val) {
        var $el = $(val)
        $el.css({top: $el.css("top")-10});
    });
}

Upvotes: 0

Shrey Gupta
Shrey Gupta

Reputation: 5617

As Wlises said, you need to stick with the jQuery methods or the core JavaScript methods; if you're using a jQuery object (which is returned in callback functions as val like in the one above), stick with the jQuery method .css().

Therefore:

  • GOOD: val.css("top","-=10")
  • BAD: val.style.top -= 10 (This is a native JavaScript property, but for jQuery objects, there is NO style property. There is only the .css() accessor/mutator method.)

Since you are trying to decrement top by 10px, it is acceptable to use: val.css("top","-=10")

Here's an explanation straight from the jQuery documentation:

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.

Upvotes: 1

wrivas
wrivas

Reputation: 509

In the "function(index, val)" the "val" is a jQuery object, try:

function moveSpans() {
    $("#myObstacles span").each(function (index, val) {
        $(val).css({top: -10});
    });
}

Upvotes: 0

Related Questions