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

Dynamically created HTML elements don't work with event listeners. >:[

In short, I wanted to implement drag and drop in my chess (like you can drag chess pieces). But something is wrong.

Problem:
The dynamically created chess piece (the one to the right) has the required event listener in its property lists, since I first dynamically create it, and only then add an event listener to each. But it doesn’t work. For example, I put another chess piece (the one on the left) created in html. And everything works on it.

Problem preview (img)

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

HTML:

<body>
    <div id="chess_field">
        <button class="place" id="place11">
            <div class="figure wp" id="" draggable="true"></div>
        </button>
        <button class="place" id="place12">
        </button>
        <button class="place" id="place13">
        </button>
        <button class="place" id="place14">
        </button>
        <button class="place" id="place15">
        </button>
        <button class="place" id="place16">
        </button>
        <button class="place" id="place17">
        </button>
        <button class="place" id="place18">
        </button>
    </div>
    <script defer src="scripts_ui.js"></script>
</body>

JavsScript:

let chessField = [[0, 0, 0, "wp", 0, 0, 0, 0]];

let dragged_element;

function DragEventAdd() {
    let figure = window.document.querySelectorAll(".figure");
    figure = Array.from(figure);
    figure.map((f) => {
        f.addEventListener('dragstart', (event) => {
            console.log("drag started");
        });
    });
}

function arrangeFigures() {
    chessField.map((i, y) => {i.map((j, x) => {
            if (j !== 0) {
                let place = window.document.getElementById(`place${y+1}${x+1}`);
                let figure = document.createElement("div");
                figure.classList.add("figure");
                figure.classList.add(j);
                figure.setAttribute("graggable", true);
                place.appendChild(figure);
            }
        })});
        debugger;
    DragEventAdd();
}

let place_drop = window.document.querySelectorAll(".place");
    place_drop = Array.from(place_drop);
    place_drop.map((pd) => {
        pd.addEventListener('drop', (event) => {
            dragged_element = "";
        });
    });
arrangeFigures();

CSS:

body {
  width: 100vw;
  height: 100vh;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

#chess_field {
  width: 80vh;
  height: 80vh;

  display: flex;
  flex-wrap: wrap;
}

.place {
  width: 10vh;
  height: 10vh;
}

.figure {
  width: 100%;
  height: 100%;
  background-size: contain;
  background-color: aqua;
}

.wp {
  background-image: url(img/wp.png);
}

Code description:
The variable "chessField" is a two-dimensional array containing information about where the chess pieces are.

"arrageFigures" function – deals with adding chess pieces to cells with "place" classes.

Function "DragEventAdd" – ADDS EVENT LISTENERS TO THEM.

I rummaged through the entire StackOverflow, and all the problems associated with this were caused by the fact that people did not give event listeners to newly created elements. But that doesn’t seem to be the problem.

>Solution :

quick fix

 function arrangeFigures() {
    chessField.map((i, y) => {i.map((j, x) => {
        if (j !== 0) {
            let place = 
              window.document.getElementById(`place${y+1}${x+1}`);
            let figure = document.createElement("div");
            figure.classList.add("figure");
            figure.classList.add(j);
            figure.setAttribute("draggable", true);
            place.appendChild(figure);
        }
    })});
   
     DragEventAdd();

}

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