Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the clicked object that triggered jquery blur() event [duplicate]

Suppose I do this:

$(target).blur(function(e){
  //do stuff
});

Is there a way to fetch the object that was clicked on in order to trigger the blur action?

I tried using e.target, but that appears to be returning the object attached to the blur action rather than the clicked object.

like image 397
pillarOfLight Avatar asked Jul 18 '12 15:07

pillarOfLight


3 Answers

The trick is to wait an extra tick:

$(el).blur(function (event) {     // If we just hangout an extra tick, we'll find out which element got focus really     setTimeout(function(){        document.activeElement; // This is the element that has focus     },1); }) 
like image 186
blockhead Avatar answered Sep 19 '22 03:09

blockhead


If I understand your question correctly, this should do it:

$(function() {      var clicky;      $(document).mousedown(function(e) {         // The latest element clicked         clicky = $(e.target);     });      // when 'clicky == null' on blur, we know it was not caused by a click     // but maybe by pressing the tab key     $(document).mouseup(function(e) {         clicky = null;     });      $(target).blur(function(e) {         console.log(clicky);     });​​  }); 
like image 33
daryl Avatar answered Sep 20 '22 03:09

daryl


Inside an event handler, this will be the element the event is bound to, and e.target will be the element that triggered the event (may or not be the same as this).

You are handing a blur event, not a click event. So, inside your event, you will have the element that you blured. If you want the clicked element, you'd need another event to get that.

blur can be triggered by other events, such as focusing something; not just clicking on something. So, there is no way to get the element that "caused the blur".

like image 42
Rocket Hazmat Avatar answered Sep 17 '22 03:09

Rocket Hazmat