<body>
<div class="button_container">
<button class="colored_button">
I'm colored red
</button>
<button class="colored_button">
I'm colored red
</button>
<button class="colored_button">
I'm colored red
</button>
</div>
</body>
.button_container{
display: flex;
gap: 3rem;
align-items:center;
justify-content:center;
padding-top:3rem;
}
.colored_button {
border-radius: 5px;
width: max-content;
height: 3rem;
color: white;
font-size: 2rem;
background-color: red;
cursor: pointer;
}
const button = document.querySelector(".colored_button");
const button_container = document.querySelector(".button_container")
let current = true;
//Event handler function
function handleClick(e) {
const clicked_button = e.target
if (current) {
clicked_button.textContent = "I'm colored blue";
clicked_button.style.backgroundColor = "blue";
current = !current;
} else {
clicked_button.textContent = "I'm colored red";
clicked_button.style.backgroundColor = "red";
current = !current;
}
}
//Add event listener to parent element
button_container.addEventListener('click', function(e){
//determine where the event originated from
if(e.target.classList.contains("colored_button")){
handleClick(e)
}
})
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.