AddEventListener only works on the last object

In the following code, it seems that I am getting a call to "otherboxclick" for the last added box (b1). If I change the order the boxes are added, it will always only be the last one to work.

How can I make it work for all boxes?

<html>
<head>
</head>
<body>

<script type="text/javascript">
    function otherboxclick(e){
        alert("other clicked");
    }

    function color_toggle_box(boxid, color, width, height, xpos, ypos)
    {
        this.boxid = boxid;

        document.body.innerHTML += 
            "<div id='" + boxid + "'; '; style='position:absolute;left:" + xpos + "px;top:" + 
            ypos +"px;width:" + width + "px;height:" + height + 
            "px;background:#000'></div>";


        this.boxdiv = document.getElementById(boxid);
        this.boxdiv.style.background = color;
        this.boxdiv.addEventListener('click', otherboxclick, true);
    }

    var b2 = new color_toggle_box("223", "#ff0", 100, 100, 205, 100);
    alert("b2 = " + b2.boxid);
    var b3 = new color_toggle_box("323", "#0ff", 100, 100, 100, 205);
    alert("b3 = " + b3.boxid);
    var b1 = new color_toggle_box("123", "#0f0", 100, 100, 100, 100);
    alert("b1 = " + b1.boxid);
</script>

</body>
</html>

      

+2


source to share


2 answers


    function color_toggle_box(boxid, color, width, height, xpos, ypos)
    {
        this.boxid = boxid;

        this.boxdiv = document.createElement('DIV');
        this.boxdiv.id = boxid;
        this.boxdiv.style.position = 'absolute';
        this.boxdiv.style.left = xpos + "px";
        this.boxdiv.style.top = ypos + "px";
        this.boxdiv.style.width = width + "px";
        this.boxdiv.style.height = height + "px";
        this.boxdiv.style.backgroundColor = color;

        document.body.appendChild(this.boxdiv);
        this.boxdiv.addEventListener('click', otherboxclick, true);
    }

      



+2


source


To explain why Lior's code works and yours doesn't:

document.body.innerHTML +=

      



is always a mistake. It turns your document objects into a string of HTML, adds some text to that string, then re-parses all of the HTML to create new document objects that replace any old ones.

This will work at best, but it will be slightly slower. However, the worst side effect is that any information that is not serialized to HTML will be completely lost. This includes form field values, JavaScript properties and links, and event listeners. This way, every time you create a color_toggle_box, you destroy any objects that previously had listeners; therefore listeners will never be named.

+1


source







All Articles