Home > OS >  Event returns [object MouseEvent] rather than the text
Event returns [object MouseEvent] rather than the text

Time:11-19

I have my p tag which suppose to chage text when I trigger mouseover event but somehow I got [object MouseEvent] in return and not the text.

HTML

    <p id="album-name-1"
      onm ouseover="changeText('follow me around, greatest song of the album!')">
      change the text
    </p>

JS

      var par = document.querySelector("#album-name-1");

      par.addEventListener("mouseover", changeText);

      function changeText(text) {
        if (this.id === "album-name-1") {
          par.innerHTML = text;
        }
      }

I wanted to do this with the use of the "this" keyword, but somehow it's not working as I expect it to work. Any suggestions?

CodePudding user response:

It's because you're adding a mouseover event listener with addEventListener, and the first parameter of the callback is the event.

Instead, you can pass this as a parameter inside the onmouseover attribute.

var par = document.querySelector("#album-name-1");

function changeText(elem, text) {
  if (elem.id === "album-name-1") {
    par.innerHTML = text;
  }
}
<p id="album-name-1" onmouseover="changeText(this, 'follow me around, greatest song of the album!')">
  change the text
</p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Don't use event attributes. They are full of hard to debug quirks and will bite you someday.

Instead, if you really want to have that text in the markup, store it in a data- attribute and retrieve it from your event handler, that you attached through addEventListener.

var par = document.querySelector("#album-name-1");

par.addEventListener("mouseover", changeText);

function changeText(evt) { // first param is the Event object
  if (this.id === "album-name-1") { // 'this' is the current target
    // all the data- attributes of our element
    // are stored in its .dataset property
    par.innerHTML = this.dataset.text;
  }
}
<p id="album-name-1" data-text="follow me around, greatest song of the album!">
  change the text
</p>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related