Reputation: 3
I know that if you create div inside div and let them call one function onclick event, it suppose to call the last one, and then the first and you can easily control this with canceling bubbling method and so on.
It's not happen with events I add to the document. For example I have a dialog and an overlay opened, I wish to close them with pressing 'Escape', but it always first closes the dialog, and then the overlay, which is kind of weird. I want to close my overlay and stop, but it seems unreal now for me. Do you have any suggestions?
Tried using methods like capture or stop bubbling, but it always goes the same
<html>
<head>
</head>
<body>
<script>
function closingChat(e){
if(event.key === 'Escape')
console.log('im closing chat')
}
function closingOverlay(e){
if(event.key === 'Escape')
console.log('im closing overlay')
}
function closingChatClick(){
console.log('im closing chat with click')
}
function closingOverlayClick(){
console.log('im closing OVERlay with click')
}
document.addEventListener('keydown',closingChat)
document.addEventListener('keydown',closingOverlay)
</script>
<div onclick="closingChatClick()">
<p onclick="closingOverlayClick()">heY</p>
</div>
</body>
</html>
Upvotes: 0
Views: 91
Reputation: 7891
The code executes in the order you mentioned, this has nothing to do with event bubbling
.
document.addEventListener('keydown',closingChat)
document.addEventListener('keydown',closingOverlay)
keydown
event is attached to the document
, when the key is pressed it will first execute closingChat
function and then closingOverlay
function.
If you want to call only closingOverlay
remove this document.addEventListener('keydown',closingChat)
.
function closingChat(e) {
if (event.key === 'Escape')
console.log('im closing chat')
}
function closingOverlay(e) {
if (event.key === 'Escape')
console.log('im closing overlay')
}
function closingChatClick() {
console.log('im closing chat with click')
}
function closingOverlayClick() {
console.log('im closing OVERlay with click')
}
document.addEventListener('keydown', closingOverlay);
<div onclick="closingChatClick()">
<p onclick="closingOverlayClick()">heY</p>
</div>
Upvotes: 1