capture phase for events
by Alexander Zonov
HTML
<div class="screen">
<div class="parent">
<a href="google.com" class="aim"></a>
<a href="ayndex.com" class="aim-absolute"></a>
</div>
</div>
CSS
.parent {
position: relative;
}
.aim {
display: block;
width: 100px;
height: 100px;
background-color: red;
position: relative;
z-index: 10;
}
.aim-absolute {
width: 200px;
height: 200px;
background-color: green;
position: absolute;
top: 0;
left: 0;
}
JavaScript
var screen = document.querySelectorAll('.screen')[0];
var parent = document.querySelectorAll('.parent')[0];
screen.addEventListener('click', function(e) {
if (e.target.classList.contains('aim')) {
e.preventDefault();
e.stopPropagation();
console.dir('capture: click on our link');
} else {
e.preventDefault();
console.log('capture: other link');
}
}, {capture: true});
screen.addEventListener('click', function(e) {
if (e.target.classList.contains('aim')) {
e.preventDefault();
console.dir('no capture: click on our link');
} else {
e.preventDefault();
console.log('no capture: other link');
}
}, {capture: false});
parent.addEventListener('click', function(e) {
console.dir('men on the middle');
}, false);