-1

I'm new to Javascript and just trying to understand the language better. I was having some trouble using the onclick function and figure out how to make it work - however I'm hoping someone could explain to me why my code in line 2 doesn't work (i've tried "reveal;" "reveal();" and "reveal(this);" ) but line 3 works.

https://plnkr.co/edit/8YlEDwABSvvGDBcotFSE

var clickButton = document.getElementById("button");
clickButton.onclick = reveal(this); // this code doesn't work
//clickButton.setAttribute("onClick", "reveal(this)"); // but this one does
function reveal(obj) {
this.obj = obj;
obj.innerHTML = "X";
}

Thank you and much appreciate everyone's input.

Phuc Duong
  • 36
  • 2
  • 2
    the `this` being passed to it is more than likely the reference `[Window]` object. Also, you should use something like `clickButton.addEventListener('click', reveal)` instead. – Jhecht Feb 11 '17 at 21:52
  • Welcome to StackOverflow! Possible duplicate: [How does the “this” keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work). In your example, if you need more information about `this`. Try to add `console.log(obj)` in `reveal` function to check what's happen in the console. – Tân Feb 11 '17 at 22:02

2 Answers2

1

The argument being passed to reveal will be an event. You can access the element via event.target. You don't need to access this at all. Please remember that setting .onclick via JavaScript is considered bad practice.

Working:

var clickButton = document.getElementById("button");

clickButton.onclick = reveal;

function reveal(event) {
    event.target.innerHTML = "X";
}

Better, using addEventListener:

var clickButton = document.getElementById("button");

clickButton.addEventListener("click", reveal);

function reveal(event) {
    event.target.innerHTML = "X";
}
Moritz Mahringer
  • 610
  • 5
  • 14
0

First:

The onclick property should hold a reference to a function that will be called when the event occur. You are not assigning a reference to a function, you are assigning the return value of that function (by executing it). This is how you do it:

clickButton.onclick = reveal; // assigning the reference to the function reveal not its return value (which is undefined by the way, because it returns nothing)

Second:

The only parameter passed to event listeners is an event object. If you want to get the object that fired the event you should access the target property of that event object like this:

function reveal(ev) { // reveal will get only one argument which is the event object
    var elementThatFiredTheEvent = ev.target; // ev.target will be the DOM element that fired the event

    // do stuff with elementThatFiredTheEvent like changing the innerHTML ...
}
ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61