1

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...

  • 2
    what does `$(this)` refer to in this case? (and no, you can't pass it that way.) – Kevin B Apr 15 '13 at 19:37
  • Inside a click event handler, the `this` is the DOM element that was clicked on. – Lee Meador Apr 15 '13 at 19:40
  • @LeeMeador Right, but he isn't inside a click event handler yet. My guess is he's binding this click event handler inside of another event, which is probably a bad idea to begin with. – Kevin B Apr 15 '13 at 19:40
  • 1
    The JavaScript `apply` and `call` might be interesting here. – Lee Meador Apr 15 '13 at 19:43

4 Answers4

5

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

$('#selected').click(function(){
    dosomething($(this))
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Yes, I want `dosomething` to accept a jquery object argument, in this case the `$('#selected')`. About the code, is that the only way I can pass `$(this)`? Meaning passing $(this) to the `$('#selected').click(dosomething)` format is not possible? Thanks for the answer! – Michael Cuna Apr 15 '13 at 19:49
1

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));
});
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

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

Bene
  • 1,875
  • 14
  • 14
0

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.

Nux
  • 9,276
  • 5
  • 59
  • 72
  • You might want to mention that he can do `var currentThis = $(this);` and then use that saved `this` value. – Lee Meador Apr 15 '13 at 19:44