0

I try to change a paragraph by hovering over it.

HTML

<p id="foo"> Hello world! </p>

Javascript

var foo = document.getElementById("foo");
foo.addEventListener("mouseover", ChangeText("Goodbye world!"));

function ChangeText(s) {
    this.innerHTML = s;
}

Yet the paragraph doesn't change on hover. When the parameter is left out and the string is directly typed like below it does work. Why?

var foo = document.getElementById("foo");
foo.addEventListener("mouseover", ChangeText);

function ChangeText() {
    this.innerHTML = "Goodbye world!";
}

1 Answers1

1

The addEventListener wants a function as a second argument; so, if you call a function with an argument, you might write :

foo.addEventListener("mouseover", function(event){
        ChangeText("Goodbye world!",event.target)
     });

function ChangeText(s,target) {
    target.innerHTML = s;
 }
Stéphane Ammar
  • 1,454
  • 10
  • 17
  • Unfortunately this also doesn't work for me. –  Dec 26 '17 at 16:59
  • 1
    The `this` value doesn't refer the `foo`. You can either update `ChangeText` to set `foo.innerHTML` or use the [Function.prototype.call()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) to invoke the function with `this` set to `foo` (`ChangeText.call(foo, "Goodbye world!")`). – Raymond Zhou Dec 26 '17 at 17:31