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.....
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With