0

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.

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.