Home > OS >  Changing text of HTML element using Javascript class and addEventListener
Changing text of HTML element using Javascript class and addEventListener

Time:09-11

I want to change the text of an HTML div using a Javascript class object by attaching addEventListener function to an HTML button. When the button is clicked, instead of displaying "Red" in the div, the "undefined" text is shown. However, if I directly call the function changeColor using a class object, the right value is shown. I apologize for such a naïve query being newer to the field. I am following tutorials on w3schools. My code is below:

class Header {
  constructor() {
    this.mystring = "Red";
  }

  changeColor() {
    document.getElementById("div1").innerHTML = this.mystring;
  }
}

//create object of class
const myheader = new Header();

// This code does not work and shows undefined in the div   
document.getElementById("btn").addEventListener('click', myheader.changeColor);

// This code works and shows Red in the div
// myheader.changeColor();
<button id="btn">Click Me!</button>

<div id="div1"></div>

CodePudding user response:

You sent myheader.changeColor function as a parameter without its context. Just use bind method.

class Header {
  constructor() {
    this.mystring = "Red";
  }

  changeColor() {
    document.getElementById("div1").innerHTML = this.mystring;
  }
}

//create object of class
const myheader = new Header();

// This code does not work and shows undefined in the div   
document.getElementById("btn").addEventListener('click', myheader.changeColor.bind(myheader));

// This code works and shows Red in the div
// myheader.changeColor();
<button id="btn">Click Me!</button>

<div id="div1"></div>

  • Related