Lern-X Lern-X - 2 months ago 6
Javascript Question

Wrapped clickable DivElement : event isn't listened

Please, consider the little following code :

function Movable(x, y, width, height, background_color) {
this.html_element = document.createElement("div");

this.html_element.onclick = this.move;
this.move = function() {
alert("Clicked !");
};

this.display = function() {
document.body.innerHTML += this.html_element.outerHTML;
};
}


I'm trying to add the HTML attribute "onclick" with "move();" as value. This
move
value is actually a function that alerts "Clicked !" when the final-user clicks on this HTML element.

But it doesn't work. When I inspect the source, it seems that the property
onclick
isn't added to this HTML element.

Do you know why and how I could solve this problem ?

Answer

document.body.innerHTML += this.html_element.outerHTML; is the problem. That's just about the worst way to go about adding an element to a page.

Your handler has nothing to do with HTML, so it is being lost when you serialize the element to HTML with the outerHTML call. Not to mention that you're serializing and destroying all the nodes under the document.body, and then turning them back into new nodes, which will make them lose and other data too.

Instead just do

document.body.appendChild(this.html_element)

Also, you're assigning this.move as the handler before you create it, which will just assign undefined unless there's a Movable.prototype.move with a handler.

function Movable(x, y, width, height, background_color) {
    this.html_element = document.createElement("div");

    this.move = function() {
        alert("Clicked !");
    };

    this.html_element.onclick = this.move;

    this.display = function() {
        document.body.appendChild(this.html_element);
    };
}