<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Bubbling</title>
<style>
.hide {
display: none;
}
</style>
</head>
<body>
<!-- The section is an example of event bubbling-->
<section onclick="alert('Section clicked!')">
<p onclick="alert('Paragraph clicked!')">I am a Paragraph
<button onclick="alert('Button clicked!')">Click</button>
</p>
</section>
<!--This div is an example of stopping event bubbling (see event.stopPropagation(); in JS file)-->
<div id="container">
Click to Hide
<button id="changeColor">Change Color</button>
</div>
<script src="app.js"></script>
</body>
const button = document.querySelector('#changeColor');
const conatiner = document.querySelector('#container');
button.addEventListener('click', function (event) {
container.style.backgroundColor = makeRandomColor();
event.stopPropagation();
})
container.addEventListener('click', function() {
container.classList.toggle('hide');
})
const makeRandomColor = function () {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
return `rgb(${r}, ${g}, ${b})`
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.