Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I be using "this" or "event.target" in javascript?

I have created a simple div demonstration below, that will display none once click.

<div id="three" onclick="toggle2(event);return false;" style="background:#303; color:#FFF;">

function toggle2(e) {

    var textx = (e.target) ? e.target : e.srcElement;
    textx.style.display = "none";

    console.log(e.target);
} 

my question is what is the difference if I replace

<div id="three" onclick="toggle2(event);return false;" style="background:#303; color:#FFF;">

with

<div id="three" onclick="toggle2(this);return false;" style="background:#303; color:#FFF;">

both of them work fine for my example abovee.....

like image 688
Vincent Chua Avatar asked Dec 09 '22 14:12

Vincent Chua


1 Answers

It may well be that they are exactly the same. This depends on the HTML. In this case, this will always be the div element. this refers to the element where the event is captured. event.target, however, points to the element where the event originated.

If the element has no children, they will always be the same. If, however, you had something like this:

<div id="three" onclick="toggle2(event);return false;" style="background:#303; color:#FFF;">
    <span>Line 1</span>
    Line 2
</div>

then they may be different. A click on Line 1 will cause event.target to be the span element, so only that element will be hidden.

Unless you specifically want to point to the element where the event originated, it's more intuitive to use this.

like image 62
lonesomeday Avatar answered Dec 11 '22 10:12

lonesomeday