Thomas
Thomas

Reputation: 323

Simple inquiry on a very small jQuery plugin

Here's a fairly newbish question: Testing out a simple function where it fades out on hover and fades back in on mouseout. Was playing around with parameters so please excuse how this doesn't make a whole lot of sense, but I just wanted to use 'opacity' in the parameter instead of hardcoding it (again, just to understand things). Here is my code:

$.fn.hoverImage = function(property) {
    //add event handler for each image (otherwise it will add the same event handler for all images all at once)
    this.each(function() {
        var img = $(this);
        //hover: first function is for mouseover, second is on mouseout
        img.hover(function() {      
            img.animate({
                property:0
            }, 200);
        }, function() {
            img.animate({
                property:1
            }, 200);
        });
    });
}

I call it doing:

$('.project-img').hoverImage('opacity');

If I write opacity as a string in the parameter it doesn't work, and if I don't put it in a string I get this error:

Uncaught ReferenceError: opacity is not defined

Just want to know why. It does work if I use the word opacity in the plugin, just to clarify that. Thanks.

Upvotes: 0

Views: 59

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use bracket notation as the member operator, because your property key is stored in a variable

$.fn.hoverImage = function (property) {
    //add event handler for each image (otherwise it will add the same event handler for all images all at once)
    this.each(function () {
        var img = $(this);
        //hover: first function is for mouseover, second is on mouseout
        img.hover(function () {
            var opts = {};
            opts[property] = 0;
            img.animate(opts, 200);
        }, function () {
            var opts = {};
            opts[property] = 1;
            img.animate(opts, 200);
        });
    });
}

Demo: Fiddle

Upvotes: 0

icktoofay
icktoofay

Reputation: 128991

The code

{property: 0}

creates an object with a property named property with a value of 0. In particular, it does not look up a variable named property and use that as the property name. If you wanted to do that, you'd have to break it out:

var obj = {};
obj[property] = 0;
/* use obj */

Compare this to using obj.property, which, too, would not use the property variable.

Upvotes: 2

Related Questions