On this page: https://developer.mozilla.org/en/DOM/element.addEventListener
It is warned that the value of this will be different when calling the modifyText() function when using addEventListener() as opposed to applying the event using onclick='' directly in the HTML. In the page linked above, note the first example (actually it’s the second), and then the following section titled ‘The value of this within the handler‘.
I decided to test this, but cannot find a difference. What am I doing wrong?
addeventlistener2.html:
<html>
<head>
<title>DOM Event Example 1</title>
<style type="text/css">
#t { border: 1px solid red }
#t1 { background-color: pink; }
</style>
<script type="text/javascript">
// Function to change the content of t2
function modifyText(new_text) {
var t2 = document.getElementById("t2");
t2.innerHTML = new_text + '<br />this: <b>' + this + '</b>';
}
// Function to add event listener to t
function load() {
var el = document.getElementById("t");
el.addEventListener("click", function(){modifyText("body onload")}, false);
}
</script>
</head>
<body onload="load();">
<p>has onload in body.</p>
<table id="t">
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
</body>
</html>
addeventlistener2.html:
<html>
<head>
<title>DOM Event Example 2</title>
<style type="text/css">
#t { border: 1px solid red }
#t1 { background-color: pink; }
</style>
<script type="text/javascript">
// Function to change the content of t2
function modifyText(new_text) {
var t2 = document.getElementById("t2");
t2.innerHTML = new_text + '<br />this: <b>' + this + '</b>';
}
</script>
</head>
<body>
<p>has onclick in table:</p>
<table id="t" onclick='modifyText("boo!")'>
<tr><td id="t1">one</td></tr>
<tr><td id="t2">two</td></tr>
</table>
</body>
</html>
In the addEventListener example you are wrapping modifyText inside an other function. All the
thismagic will happen to that outer function and modifyText won’t see any of it.Try passing modifyText directly to addEventListener
Or use the power of closures if you still want to be able to choose the parameter: