Michael Cuna
Michael Cuna

Reputation: 15

jQuery: pass $(this) to a function

How can I pass the $(this) object to a function that looks like this

$('#selected').click(dosomething)

Where dosomething is the function. I tried doing things like...

$('#selected').click(dosomething($(this)))

But it seems like I'm doing it the wrong way...

Upvotes: 1

Views: 99

Answers (4)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Within the event handler jQuery will assign this to the selected element. Be aware that it is not a jQuery object at that point, so you need to wrap it with $().

$('#selected').click(function(){
   dosomething($(this));
});

Upvotes: 1

Nux
Nux

Reputation: 10002

Depends on what you are trying to acomplish:

This will be solid and will give you this of the outside:

$this = $(this);
$('#selected').click(function(){
    dosomething($this);
})

This is suffcient if you want to pass this meaning "#selected" element:

$('#selected').click(function(){
    dosomething($(this));
})

Or you can do this to run dosomething in the context of "#selected" element:

$('#selected').click(function(){
    dosomething.call(this);
})

The last will allow to use this inside dosomething function which will mean "#selected" element.

Upvotes: 0

Bene
Bene

Reputation: 1905

You're actually not so far. You already are in the $(this) scope when you add an event. So all you have to do is this:

$('#selected').click(function() {
 // $(this) is the same as $('#selected')
});

And let say you want an "outside" function like this:

function click_trigger(e) {
  // e for EVENT
  var $this = $(e.target) // The targeted selector ($('#selected'))
  // OR
  var $this = $(e.currentTarget) // The current clicked item (which might have "bubbled" to #selected)
}
$('#selected').click(click_trigger);

You can look the jquery documentation for more information on the "event" parameter

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382102

If dosomething accepts as argument a jQuery object, then you can do this :

$('#selected').click(function(){
    dosomething($(this))
});

Upvotes: 5

Related Questions