Preventing Event Bubbling
function clickHide(){ if (MouseEvent.button === 0) hide(); } function hide(){ using.style.display = 'none'; hidden.style.display = 'none'; } I have a problem with even
Solution 1:
You should use Event.stopPropagation()
. Simply just call the stopPropagation()
method on the event you are listening to.
Also see here for more info.
Edit: You can try it like this, it will only fire the event when you click on the parent element. The if statement checks if the target of the event is the parent element then calls hide()
if not then it returns nothing.
const parentElement = document.querySelector(".parentElement");
const childElement = document.querySelector(".childElement");
parentElement.addEventListener("click", clickHide);
function clickHide(event) {
if(event.target !== parentElement){
return;
}
hide();
}
function hide() {
parentElement.classList.add('hidden');
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="" />
<style>
.parentElement {
border: 20px solid red;
}
.childElement {
background: yellow;
padding: 20px;
}
.hidden {
display: none;
}
</style>
<script src="test.js" async defer></script>
</head>
<body>
<div class="parentElement">
<div class="childElement"></div>
</div>
</body>
</html>
Post a Comment for "Preventing Event Bubbling"