Hilmi
Hilmi

Reputation: 3441

Get the element from a function that was called inside the element's event

lets assume that I have the following ...

jQuery('#a').click(function(){
   myFunction();
});
function myFunction(){
  var me = jQuery(this);// this one gets the "window" object instead of "#a" element
}

How can I get the target element that initiated the event from myFuncton while I cant send this as parameter because its going to coast me to go back and re-check the whole site and change every function call arguments ...

Upvotes: 2

Views: 105

Answers (3)

eloycm
eloycm

Reputation: 414

jQuery('#a').click(function(){
   myFunction(this);
});
function myFunction(sender){
  if (sender !=undefined)
   {
      var me = jQuery(sender);// and do other stuff
      //.....
   }
   //do your old stuff -- me will be logically out of scope
}
//this will not result in an error, sender will be undefined
// the code will be compatible backwards
myfunction();

Upvotes: 0

xdazz
xdazz

Reputation: 160833

So you could just do:

$('#a').click(myFunction); // then this in myFunction will be the '#a' element.

Update:

If you need to do other thing in the callback other then myFunction, then you could try .call() or .apply() to execute a function with a given this value.

$('#a').click(function() {
    otherLogic();
    myFunction.call(this);
});

Upvotes: 4

Sushanth --
Sushanth --

Reputation: 55740

Try this

jQuery('#a').click(function(){
   myFunction(this);
});

function myFunction(elem){
  var me = jQuery(elem);
}

You will get the current object that called the function in the elem as you passed it from the click event

Upvotes: 1

Related Questions