Keith Costa
Keith Costa

Reputation: 1793

How to set multiple css using jquery animate function

suppose i have css like

position: fixed;
width: 200px;
height: 100px;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -50px;

this css i need to set from jquery animate function for div. is it possible. i know the use of jquery animate function like

$(".ui-dialog").animate({
left: viewportwidth / 2 - $(".ui-dialog").outerWidth() / 2, 
top: viewportheight / 2 - $(".ui-dialog").outerHeight / 2
}, 1000);

thanks

Upvotes: 0

Views: 4137

Answers (3)

Pedram Behroozi
Pedram Behroozi

Reputation: 2497

Yes, it is possible but take care of two things:

  1. You can't animate position:fixed. (Quote from jQuery .animate() manual):

    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

    Use classes to handle this.

  2. Use marginTop and marginLeft instead of margin-top and margin-left. (Quoted from Ricardo Vega's answer on SO):

    try using "marginTop" instead of "margin-top". Normally when you use the CSS props as "border-something" or "margin-something" is better to use the "normalized" version of it, as you used to do it in DHTML (styles.marginTop).

Hope it helps.

Upvotes: 1

Luke
Luke

Reputation: 23680

Create the CSS as a class:

div.myClass {

    position: fixed;
    width: 200px;
    height: 100px;
    top: 50%;
    left: 50%;
    margin-left: -100px;
    margin-top: -50px;

}

div.newClass {

    position: fixed;
    width: 500px;
    height: 500px;
    top: 50%;
    left: 50%;
    margin-left: -100px;
    margin-top: -50px;

}

Then dynamically add the class to the DIV element by using jQuery addClass()

$("div#myDiv").addClass("myClass");

This assumes that your DIV has the ID of myDiv like so:

<div id="myDiv"></div>

If you need to animate from it's current class to another one, you can use the switchClass() function:

This is an example of changing the class on a binding to a button

<script>
$(function() {
    $( "#button" ).click(function(){
        $( "div#myDiv" ).switchClass( "myClass", "newClass", 1000 );
    return false;   
    });
});
</script>

Upvotes: 4

Al-Mothafar
Al-Mothafar

Reputation: 8219

Your code working with me as it is :)

But if you use "viewportwidth" & "viewportheight" with "px" or "em" or what ever, use ".parseInt()" to eliminate unit :)

My code is :

var viewportwidth = 120;
var viewportheight = 120;
$(".ui-dialog").animate({
left: viewportwidth / 2 - $(".ui-dialog").outerWidth() / 2 +"px", 
top: viewportheight / 2 - $(".ui-dialog").outerHeight() / 2 +"px"
}, 1000);

});

BTW, I see you miss parentheses after "outerHeight" and the code working me with & without +"px" in FF, I hope I understood you correctly .

Upvotes: 0

Related Questions