SDE1🏢 Zeta DOM / UI Component
Preview selected color from swatches
Implementation & Test Harness
Editable Monaco RunnerJavaScript Lab Sandbox
<!DOCTYPE html>
<html>
<head>
<title>SDE1 - Zeta | Preview Selected Color From Swatches</title>
<style>
#display-area {
width: 100px;
height: 100px;
border: 2px solid black;
margin-bottom: 10px;
}
#color-swatches {
display: flex;
align-items: center;
gap: 4px;
}
.color-box {
width: 30px;
height: 30px;
border: 1px solid black;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.purple {
background-color: purple;
}
.pink {
background-color: pink;
}
.yellow {
background-color: yellow;
}
.white {
background-color: white;
}
</style>
</head>
<body>
<section>
<div id="display-area">
</div>
<div id="color-swatches">
<div class="color-box red"></div>
<div class="color-box blue"></div>
<div class="color-box green"></div>
<div class="color-box purple"></div>
<div class="color-box pink"></div>
<div class="color-box yellow"></div>
<div class="color-box white"></div>
</div>
</section>
<script>
function sampler(fn, count, context) {
let counter = 0;
return function (...args) {
let lastArgs = args;
context = this ?? context;
if (++counter !== count) return;
fn.apply(context, args);
counter = 0;
};
};
const displayAreaElm = document.querySelector("#display-area");
const colorBoxElms = document.querySelectorAll(".color-box");
colorBoxElms.forEach((e) => {
e.addEventListener('click', sampler((f) => {
const compStyle = getComputedStyle(e);
const bgColor = compStyle.getPropertyValue("background-color");
displayAreaElm.style.backgroundColor = bgColor;
}, 4));
});
</script>
</body>
</html>Console Output
Click "Run Code" above to execute and view output...