<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Copy content on click</title>
</head>
<body>
<div class="colors-to-choose">
<div class="color" style="background: rgb(55, 175, 233);">#37AFE9</div>
<div class="color" style="background: rgb(52, 75, 100);">#344B64</div>
<div class="color" style="background: rgb(153, 222, 255);">#99DEFF</div>
<div class="color" style="background: rgb(250, 251, 251);">#FAFBFB</div>
<div class="color" style="background: rgb(233, 235, 243);">#E9EBF3</div>
<div class="color" style="background: rgb(255, 255, 255);">#FFFFFF</div>
<div class="color" style="background: rgb(0, 110, 169);">#006EA9</div>
</div>
</body>
</html>
.colors-to-choose {
display: flex;
justify-content: center;
flex-wrap: nowrap;
&>div {
padding: 10px;
margin: 20px 5px 0;
}
}
View Compiled
var color = document.querySelectorAll('.color') //DOM selector
//Loop through all elements and attaching event listener
color.forEach(el => {
el.addEventListener('click',copyText)
})
// function for selecting the text of an element based on the event.target (supporting IE)
function selectText() {
var element = event.target
var range;
if (document.selection) {
// IE
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
// function for copying selected text in clipboard
function copyText() {
selectText();
alert('Color code ' + event.target.innerText + ' copied in clipboard')
document.execCommand("copy");
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.