I want to create a DOM element that changes its color when clicked on. The DOM object is appended to document.body
by the draw()
method that belongs to the Rectangle
class.
I want the Rectangle constructor()
method to add the EventListener("click", ...)
to the object itself, but it can't call the select()
method, which also belongs to Rectangle
class.
I get the error message select() is not a function
. I can't write addEventListener("click", this.select(true))
because for some reason, the rectangle is already selected when the HTML document is loaded.
On the other hand, when I try addEventListener("click", function() { this.select(true) });
I get the error message this.select() is not a function
.
This is my code:
class Rectangle {
constructor(id) {
this.id = id;
this.selected = false;
this.draw();
document.getElementById(this.id).addEventListener("click", select(true));
}
draw() {
//puts the element on the screen
}
select(_isSelected) {
if (_isSelected == true) {
this.selected = true;
//this method also modifies the DOM element style
}
}
}
function start() {
var firstRect = new Rectangle("sth");
}
The start()
function is called at the end of HTML document.