Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


    <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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading