4

when to use $(this) and e.target?

I don't have confusion for $(this), but e.target for me is confusing because it can perform the same thing as $(this). (or I'm wrong?)

$(document).on('click',"div", function(){
        $(this).css('color', 'red');
    }
});

vs

$(document).on('click',"div", function(e){
        $(e.target).css('color', 'red');
    }
});

2 Answers2

8

They will be the same if you clicked on the element that the event is rigged up to. However, if you click on a child and it bubbles, then this refers to the element this handler is bound to, and e.target still refers to the element where the event originated.

Kiran
  • 20,167
  • 11
  • 67
  • 99
  • You can detect this with javascript:`e.target==this` or for older I.E `e.srcElement ? e.srcElement==this : e.target==this` – dgo Sep 08 '13 at 13:10
3

The e.target property can either be the element that registered the event or a descendant of of that element. You can compare it to $(this) to determine if an event delegation occurred due to event bubbling.

zoranc
  • 2,410
  • 1
  • 21
  • 34
  • descendant of of that element? why? so you are trying to say e.target is better because it prevent event bubbling problem? –  Sep 08 '13 at 12:31
  • no, I'm not saying one is better than the other...you can use e.target to get the child that triggered the event. If you want to stop event bubbling you would have to invoke e.stopPropagation() – zoranc Sep 08 '13 at 12:40
  • your example doesn't show if you are using any child elements, hence assuming that it is just one element with no children both e.target and $(this) will be pointing to the same element that triggered the event. – zoranc Sep 08 '13 at 12:41
  • Indeed, neither "better" nor "worse", but "different under some circumstances". – Beetroot-Beetroot Sep 08 '13 at 12:42