Search code examples
javascripthtmladdeventlistenergun

Why after adding elements to the document the addEventListener stop working?


I have two .addEvenetListener in my code but one of them stop working after adding a div to my

document.addEventListener("mousemove", (e) => { mouseMove(e) }, false);
document.body.addEventListener("click", function(e){
    e = e || window.event;  
    if (e.which == 1) fire();
}, false);

function fire(){
    let bullet = `<div class="bullet" style="left:${shooterPlace.x}px;top:${shooterPlace.y}px;"></div>`;
    document.getElementById("space").innerHTML += bullet;
}

After clicking, the GUN that I made stops rotating due to the stop of the eventlistener

HTML:


    <div class="body-copier" id="space">
        <div id="gun">
            <div id="gun-shooter-place"></div>
        </div>  
    </div>


Solution

  • Try this

    let bullet = document.createElement("div");
     Object.assign(bullet,{class:"bullet",style:`left:${shooterPlace.x}px;top:${shooterPlace.y}px;`});
    
    document.getElementById("space").append(bullet);
    

    Your .space element is edited out of DOM, so it loses it's eventListeners as Your innerHtml+="something new" is the same as .innerHtml="something berfore with something new" .

    You want to add additional element to DOm but .innerHtml doesn't do this.

    Anyway You didn't provide reproducable code (html missing) so i don't know where is Your gun element (i suppose it's inside .space element)