Vitalii Isaenko
Vitalii Isaenko

Reputation: 989

Pass 'this' as an argument to event handler using on() jQuery method

I dynamically add elements with class .footprint to DOM and need to add click() event to them. My current code looks like this:

$("#pcb").on("click", ".footprint", selectFootprint);

However, selectFootprint(sender) method has a parameter where I would like to pass DOM element (this).
How can I do it?

Upvotes: 1

Views: 2193

Answers (3)

Beppe
Beppe

Reputation: 235

Instead of using selectFootprint directly as a callback, define a new function that calls selectFootprint with this as parameter (this inside an eventlistener always refers to the DOM element the listener is attached to)

$(".footprint").on("click", function() {
  selectFootprint(this);
});

Upvotes: 1

Elad
Elad

Reputation: 2377

Acutely, in on() jQuery function- this keyword is represent the clicked element, so you can call the function as you wished.

$( "#dataTable tbody" ).on( "click", "tr", function() {
  console.log( $( this ).text() );
});

(From the decomention).

Or in youre case:

function selectFootprint(){
   console.log( $( this ).text() );
}
$("#pcb").on("click", ".footprint", selectFootprint);

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138267

A few solutions (to pass the parents context):

1) using jquerys data parameter:

$("#pcb").on("click", ".footprint", this, function(e){
  console.log(this, e.data);//data is the parents this
});

2) using a closure

var sender = this;
$("#pcb").on("click", ".footprint", function(){
  selectFootprint.call(this, sender);
 });

Or if you just want to pass the .footprint :

$("#pcb").on("click", ".footprint",function(){
 selectFootprint(this);
});

Upvotes: 3

Related Questions