I'm not sure why this one is haunting me. I have a grid of event cards. Each card has a button with the same background color. How do I return the rbg value of that button class, in this exampleevent-button?
<div class="event-grid">
<div class="event-card">
<button class="event-button">Buy Tickets</button> // return r, g & b values for bg color
</div>
<div class="event-card">
<button class="event-button">Buy Tickets</button>
</div>
<div class="event-card">
<button class="event-button">Buy Tickets</button>
</div>
<div class="event-card">
<button class="event-button">Buy Tickets</button>
</div>
</div>
If you want to get the r, g, b and a value of the css class definition, you can use getComputedStyle Reference
Please find the working fiddle.
document.querySelectorAll('button.event-button').forEach((button) => {
button.onclick = function(e) {
const styles = window.getComputedStyle(e.target);
const background = styles.getPropertyValue("background-color");
const [red, green, blue, alpha] = background.replace(/^(rgb|rgba)\(/,'').replace(/\)$/,'').replace(/\s/g,'').split(',');
console.log(red, green, blue);
}
});
.event-button {
background: rgba(255,0,0,0.3);
}
<div class="event-grid">
<div class="event-card">
<button class="event-button">Buy Tickets</button> // return r, g & b values for bg color
</div>
<div class="event-card">
<button class="event-button">Buy Tickets</button>
</div>
<div class="event-card">
<button class="event-button">Buy Tickets</button>
</div>
<div class="event-card">
<button class="event-button">Buy Tickets</button>
</div>
</div>