So, when you click on the element, mouseenter
runs, even though it never left the parent, and mouseleave
does not fire.
I have checked the MDN docs, and neither of the events bubble and aren't cancellable; so why does one run when the other doesn't?
The problem goes away if you use style.display = 'none';
although then the elements aren't removed, and it doesn't work if you run both display: none
and remove()
at once.
Well I thought it ran because it thinks it leaves the parent for a split second but going by that logic mouseleave
should've run too?
e.stopPropagation()
has no effect, either
const container = document.querySelector('.container');
const reset = document.querySelector('.reset');
container.addEventListener('mouseenter', () => {
console.log('enter');
});
container.addEventListener('mouseleave', () => {
console.log('leave');
});
reset.addEventListener('click', () => {
container.innerHTML = '';
let i = 8;
while (i--) {
const block = document.createElement('div');
block.addEventListener('click', () => {
block.remove();
});
block.classList.add('block');
container.append(block);
}
});
for (const block of document.querySelectorAll('.block')) {
block.addEventListener('click', () => {
block.remove();
});
}
.container {
display: flex;
padding: 2px;
background: grey;
}
.container>.block {
width: 100px;
height: 100px;
background: black;
margin-right: 5px;
}
.reset {
color: #f3f3f3;
background: grey;
padding: 8px 16px;
position: absolute;
bottom: 10px;
right: 10px;
}
<div class="container">
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
<div class="block"></div>
</div>
<div class="reset">
Reset
</div>
Fiddle: https://jsfiddle.net/burzjpse/1/