I have a button:
<button class="badge" style="background-color: #ff3333;" data-clipboard-target="#badge">RED</button>
that I'd like to copy the color of using Clipboard.js. I understand that I can do this manually with data-clipboard-target but I was hoping to trigger the event dynamically using something like their sample code:
new ClipboardJS('.btn', {
text: function(trigger) {
return trigger.getAttribute('aria-label');
}};
I tried using about 100 variants of:
new ClipboardJS(".badge", {
text: function(trigger) {
return $(trigger).closest(".badge").element.style.backgroundColor();
}
});
but I keep getting the error: Uncaught TypeError: Cannot read property 'style' of undefined
.
I realize that I can just use data-clipboard-target and do this manually but I was hoping figure out why the targeting is off. Thanks
You have to set the data-clipboard-text
and then return the text you want copied in the text function
. Also you can use trigger.style.backgroundColor
to get the background color.
new ClipboardJS(".badge", {
text: function(trigger) {
var result = trigger.style.backgroundColor
return console.log(result) || result
}
});
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="badge" style="background-color: #ff3333;" data-clipboard-text="">RED</button>