I have a div called starter-box that when clicked is supposed to dynamically create 2 divs. I added an event listener to the parent of the starter-box div to listen for any event of the 2 dynamically created divs.
The problem is that the click event listener conflicts with the mousedown event listener preventing it (the click event) from executing.
document.addEventListener('DOMContentLoaded', function () {
var container = document.querySelector("#container");
var target;
var elementCreated = false;
var elements = [];
container.addEventListener("click", (ev) => {
target = ev.target;
if (target.className != "box" && target.id != "container") {
if (elementCreated == false) {
createElements(target);
} else if (elementCreated == true) {
removeElementsByClass("box");
elements = [];
}
}
});
container.addEventListener("mousedown", (ev) => {
target = ev.target;
alert("MouseDown on: " + target.id);
});
container.addEventListener("mouseup", (ev) => {
target = ev.target;
alert("MouseUp on: " + target.id);
});
function createElements(target) {
const dimensions = target.getBoundingClientRect();
const element1 = document.createElement('div');
element1.className = "box";
element1.id = "box1";
element1.style.left = (dimensions.left) + "px";
element1.style.top = dimensions.bottom + 25 + "px";
container.appendChild(element1);
const element2 = document.createElement('div');
element2.className = "box";
element2.id = "box2";
element2.style.left = (dimensions.left) + "px";
element2.style.top = dimensions.bottom + 90 + "px";
container.appendChild(element2);
}
});
#container {
width: 600px;
height: 400px;
background-color: blue
}
#starter-box {
position: relative;
top: 50px;
left: 25px;
width: 50px;
height: 50px;
background-color: red
}
.box {
position: absolute;
width: 50px;
height: 50px;
background-color: black
}
<div id="container">
<div id="starter-box">
</div>
</div>
Check the fields of event object (ev argument to the listener callback).
You can use it your logic.
Discover the event object, try to console.log(ev), and see. There are more differences.