views:

31

answers:

4

Using jQuery, I set a link tag's click handler like this:

$('#lnk').click(handleClick);

handleClick does something like this:

function handleClick() {
    var $this = $(this);
    ...
}

Now I have a need to directly call handleClick() outside of #lnk being clicked. Is there a way for me to set this when calling handleClick?

+3  A: 

You can use apply() or call():

handleClick.call(theElementThatShouldBeThis);

But of course theElementThatShouldBeThis must be a DOM element or something that is accepted as input for jQuery().

And it becomes more tricky if you are accessing the event element inside handleClick. But I will just assume you don't ;)

You can also always execute the event handler in the context of #lnk by calling $('#lnk').click() (which simulates a click).

Felix Kling
I don't see those in the jQuery API. Are those plugins? Have any links?
slolife
Those are built into javascript
Karim
@slolife: I linked to the corresponding documentation. These are methods of every function.
Felix Kling
@downvoter: How can I improve my answer? What is wrong?
Felix Kling
Yep, momentary lapse of sanity there. I had hoped I'd be able to delete that comment before it was noticed, but, nope.
ShZ
@ShZ: No worries ;)
Felix Kling
A: 

I think you're looking for "call" or "apply":

Call

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call

Apply

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply

From MDC

var result = fun.apply(thisArg, [argsArray]);

or

var result = fun.call(thisArg[, arg1[, arg2[, ...]]]); 
Karim
A: 

You might just want to trigger the click event handler on #lnk.

function some_other_place(){
    $('#lnk').trigger('click');
};

Description: Execute all handlers and behaviors attached to the matched elements for the given event type.

Reference: .trigger()

jAndy
A: 

Use Function.apply and pass in the DOM element returned by the query.

handleClick.apply($('#lnk')[0]);

Or better yet, let jQuery simulate a click on the element (Assuming you've already attached the click event handler).

$('#lnk').click();
Roy Tinker