technopeasant
technopeasant

Reputation: 7949

jQuery pass object out of one function to another

I've made a small function that I'll be reusing several times in an application. It seems like I've written the syntax wrong because my console is showing an eror "Object [object Object] has no method 'fadeIt'

So I imagine the issue is passing the object of one function into another.. not sure how to do it gracefully. My code is below.

Thanks for your help!

http://jsfiddle.net/danielredwood/aFx6u/2/

function fadeIt() {
    $(this).animate({
        opacity:0
    }, 400, function(){
        //$(this).css('cursor','auto');
        //$(this).children('img').css('margin-left','-100px');
    });
}

$('.box').click(function(){
    $(this).fadeIt();
}):

Upvotes: 0

Views: 747

Answers (4)

user1106925
user1106925

Reputation:

You can set the calling context of the fadeIt function by using .call(), like this...

fadeIt.call(this)

Explanation:

JavaScript has two methods, .call() and .apply() that both let you manually set the value of this in the function you're invoking, at the time of invocation.

The .call() and .apply() methods are available on all JavaScript functions for this purpose.

The first argument to the method is the value you want to set for this in the function you're invoking. The only difference between the two is how the arguments are passed.


With .call(), the arguments are passed individually, like...

func.call(thisArg, 'foo', 'bar')

With .apply() the arguments are passed as an Array-like collection...

func.apply(thisArg, ['foo', 'bar'])

...which will be destructured as individual arguments in the function being invoked.

Upvotes: 1

Zwade
Zwade

Reputation: 1712

What you are trying to do is call a function using dot notation, which in Javascript is limited only to an object's prototype. What you want to do is change it so you pass the this as an argument in fadeIt

function fadeIt(obj) {
...
}

then call fadeIt($(this));

Upvotes: 0

Sparky
Sparky

Reputation: 98738

This fixes your code.

function fadeIt(element) {
    element.animate({
        opacity:0
    }, 400, function() {
        // element.css('cursor','auto');
        // element.children('img').css('margin-left','-100px');
    });
}

$('.box').click(function() {
    fadeIt($(this));
}):

However, I would strongly recommend using jQuery's built in functions like fadeOut and fadeIn instead.

Upvotes: 0

MyStream
MyStream

Reputation: 2553

You probably want to make this into a plugin and use the following approach:

$.fn.fadeIt = function() {

};

then you can use $(this).fadeIt();

Upvotes: 2

Related Questions