Barrie Reader
Barrie Reader

Reputation: 10713

Authoring a plugin function with jQuery

Hey dudes, I have the following function:

$.fn.slideOut = function(speed,dir) { 
        this.animate({
            dir: '-1000px'
        }, speed);
    };

But the direction (dir) isn't being carried over and isn't giving me an error either.

I'm calling it like so: $('#element').slideOut(500,'top');

So my quesiton = why is it not animating? :(

Upvotes: 1

Views: 91

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074555

You can't use a variable on the left-hand (name) side of an object literal property initializer, what you have there is actually the property name "dir". You'll have to do it like this:

$.fn.slideOut = function(speed,dir) { 
    var opts = {};
    opts[dir] = '-1000px';
    this.animate(opts, speed);
};

A bit off-topic, but probably worth pointing out that that plug-in function won't chain. Unless you have a good reason not to, return this for chainability (in this case, you can just return what animate returns, since animate returns this):

$.fn.slideOut = function(speed,dir) { 
    var opts = {};
    opts[dir] = '-1000px';
    return this.animate(opts, speed);
};

Upvotes: 5

Martin
Martin

Reputation: 6032

you are calling

this.animate({
  dir: '-1000px'
}

in your plugin. It is normal that it doesn't use the one received as a parameter.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816590

If you want to use a variable property name, you cannot use object literals. You first have to create the object and then set the property with the "array access" syntax:

$.fn.slideOut = function(speed,dir) {
    var options = {};
    options[dir] = '-1000px';
    this.animate(options, speed);
};

Upvotes: 4

Related Questions