Chogori Posted October 15, 2015 Share Posted October 15, 2015 Can somebody explain me, why is necessary to write: childTD[i].addEventListener("click", function(){changeColor(this);}); and not just: childTD[i].addEventListener("click", changeColor(this)); Here is the whole code: var ParentTable = document.getElementById("mytable");var childTD = ParentTable.getElementsByTagName("td");for(i=0;i<childTD.length;i++) { childTD[i].addEventListener("click", function(){changeColor(this);});}function changeColor(element) { element.style.backgroundColor="red";} Thanks a lot! Link to comment Share on other sites More sharing options...
justsomeguy Posted October 15, 2015 Share Posted October 15, 2015 The first way assigns a function as the event handler that will call the changeColor function and pass it a value. The second way executes the changeColor function immediately and assigns the return value of that function as the event handler. Link to comment Share on other sites More sharing options...
Ingolme Posted October 16, 2015 Share Posted October 16, 2015 What value does "this" have in that context? You probably should just use the event object that's passed to the function instead: childTD[i].addEventListener("click", changeColor); function changeColor(e) { var element = e.target; element.style.backgroundColor="red";} 1 Link to comment Share on other sites More sharing options...
Chogori Posted October 18, 2015 Author Share Posted October 18, 2015 Ingolme, thanks, you are absolutly right! Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now