<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Events: Task 3</title>
<style>
p {
color: purple;
margin: 0.5em 0;
}
* {
box-sizing: border-box;
}
button {
display: block;
margin: 20px 0 20px 20px;
}
.button-bar {
padding: 20px 0;
}
</style>
<link rel="stylesheet" href="../styles.css" />
</head>
<body>
<section class="preview">
</section>
<div class="button-bar">
<button data-color="red">Red</button>
<button data-color="yellow">Yellow</button>
<button data-color="green">Green</button>
<button data-color="purple">Purple</button>
</div>
<script>
const buttonBar = document.querySelector('.button-bar');
// Add your code here
let btn = document.querySelector('button');
btn.addEventListener('click', (e) => {
console.log(e.target.getAttribute('data-color'));
});
</script>
</body>
</html>
in this, there are multiple button elements but when I add an event listener to the button whenever it gets clicked it shows its data-color value but the event is only firing for the first button, not for others If anyone could tell why it's behaving like this it would be great help thanks.
Instead of attaching a listener to each button add one to the container. Using event delegation you can catch the event from the clicked element as it bubbles up the DOM, and log its colour.
const buttonBar = document.querySelector('.button-bar');
buttonBar.addEventListener('click', handleClick, false);
function handleClick(e) {
// Get the nodeName, and color from
// dataset of the clicked element
const {
nodeName,
dataset: { color = 'none' }
} = e.target;
// If the clicked element is a button
// log the colour
if (nodeName === 'BUTTON') {
console.log(color);
}
}
p { color: purple; margin: 0.5em 0; }
* { box-sizing: border-box; }
button { display: block; margin: 20px 0 20px 20px; }
.button-bar { padding: 20px 0; }
<div class="button-bar">
<button data-color="red">Red</button>
<button data-color="yellow">Yellow</button>
<button>Empty</button>
<button data-color="green">Green</button>
<button data-color="purple">Purple</button>
</div>