I have a js class called Header, which, when the render () method is called, adds the html header code to all pages of the site.
This class, in addition to the render () method, also has a hello () method:
hello() {
console.log('Hello');
}
The question is, how do I add this method as an event to the header button?
I've tried doing it like this:
<button onclick="${this.hello}">Call/button>
But it displays an error in the console: Uncaught SyntaxError: Unexpected token '{'
How to add a class method as an event to a html button?
CodePudding user response:
First, create an object of your class. Then use the object to call the method.
Example:
class Header {
render(){
// render other things
// also render: <button onclick="header.hello();">Call</button>
}
hello() {
console.log('Hello');
}
// other methods here...
}
var header = new Header();
header.render();
CodePudding user response:
Did you mean something like this?
You can use HTMLelement.addEventListener
to listen for specific events like click
event on a button, and then provide a callback function to perform when that event is triggered.
const btn = document.getElementById('test');
class Header {
render(element) {
element.addEventListener('click', () => this.hello());
}
hello() {
console.log('Hello');
}
}
const header = new Header();
header.render(btn);
<button id="test">Click me</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>