views:

48

answers:

2

Is it possible to define a string of animations as a variable?

For example (this is what I think, but doesn't work?):

var speed = 500;
var dothis = $("#div").slideUp('speed');
            $("#div").slideDown('speed');
            $("#div").animate({height: "0px"}, 'speed');
$("button").click(function () { 
      $(this).dothis();
    });

I'm not totally sure how to set it up.

+1  A: 

It looks like you're trying to execute a series of actions at a later time... in which case you can just encapsulate all your commands in a function:

var dothis = function() {
    $("#div").slideUp('speed');
    $("#div").slideDown('speed');
    $("#div").animate({height: "0px"}, 'speed');
    $("button").click(function () { 
      $(this).dothis();
    });
}

And then later you can do all the commands at once by invoking the function:

dothis();
Daniel Lew
Yea! This is great! Thanks, Daniel.
Kevin Brown
+1  A: 

You could also extend Daniel's function to work with any element you passed to it by giving the function an argument. For example, passing it an element or a selector:

var dothis = function(el) {
    $(el).slideUp('speed');
    [...]

Also, not that there's a difference between putting each effect on it's own line or chaining them like $(el).slideUp().slideDown().fade() etc.

If you put them on separate lines they will execute nearly simultaneously, whereas chaining them queues them to execute in order.

Gabriel Hurley