Nathan
Nathan

Reputation: 7032

jQuery: Bind JS Function to all Selected Elements

I'm sure this is a simple question, but didn't see applicable answers here. I've got code like this:

 $('.thumbImg').mouseout(function(){selectCur()});
//selectCur() is a pure-JS function defined elsewhere in the document

But the function is only bound to the first element with class .thumbImg. Normally, I'd use a $(this), but that won't work here (unless I'm doing something wrong).

I guess my last resort is a for loop, but I'm sure there's a way to avoid that.

Thanks!

Upvotes: 0

Views: 337

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92284

Don't think it's a cache problem, it's a context problem. Fix it by passing in $this to your selectCur.

$('.thumbImg').mouseout(function(){selectCur($(this))});

Or even

$('.thumbImg').mouseout(selectCur);

Then selectCur can use $(this); I think the first solution is better since selectCur could be used from other places, so you can just pass in the node when necessary.

Upvotes: 0

Meligy
Meligy

Reputation: 36584

The reason this doesn't work is that it's local to the function() {} in your code, not the selectCur() function.

If you want to use this in selectCur(), you can do it like:

$('.thumbImg').mouseout(selectCur);

The way you do it is make an anonymous function / closure that calls your function and refer to that in mouseout. Instead of this, all you need to do is point to your function (not call it, no () in here) and it'll be called when the event fires. You don't need a function to point to a function. Just point to it and it'll work.

Upvotes: 1

Related Questions