Lee
Lee

Reputation: 3969

jQuery set css position in animate function

How would you set the position:relative property in an element that does not have an initial position property set, within jQuery's animate()?

This does not work:

$(mLinks[id]).animate
(
    {
        position:'relative',
        left:'200px'
    }
);

Given that mLinks is a valid DOM element object.

I also tried with the duration and callback parameters.

Upvotes: 1

Views: 9821

Answers (3)

Praveen Puglia
Praveen Puglia

Reputation: 5631

take a look at this code.

<html>
<head>
    <title>Hello there</title>
    <script type="text/javascript" src = "assets/js/jquery.min.js"></script>
</head>
<body>
    <div class="tobechanged" style = "background:#ddd;position:fixed;">
        hello there.
    </div>
    <script type="text/javascript">
    $('.tobechanged').css('position','relative').animate({
        opacity: 0.9,
        left: '+=50'},
        4000, function() {
        //some stuff here.
    });
    </script>
</body>
</html>

This now should work just fine.

Upvotes: 0

freedev
freedev

Reputation: 30077

The animate method don't let you to set css attributes and this make sense, although to have a great animation you must set correctly the css attributes, these are two different things.

So first you should set the css attribute. And you should use css method:

$(mLinks[id]).css("position", "relative")

After you can start with the animation:

$(mLinks[id]).animate({ left:'200px' });

Combining all together you'll have:

$(mLinks[id]).css("position", "relative").animate({ left:'200px' });

Upvotes: 2

luiges90
luiges90

Reputation: 4598

It does not make sense to "animate" the css position attribute isn't it? There is nothing between relative and absolute or static or anything like that...

This is what I would do:

$(mLinks[id]).css('position', 'relative').animate
(
    {
        left:'200px'
    }
);

If you read the corresponding jQuery doc, you will find this:

most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used).

Upvotes: 6

Related Questions