Adding Copy Buttons with Bitty
Hitting a Single
Bitty has a .quickCopy()
method. It does two things:
-
Copies the content of the target element.
-
Updates the text of the Copy button to say "Copied" for two seconds then reverts it.
For example:
Copy
The quick brown fox
;
The quick brown fox
Connecting Keys
You can put multiple buttons on a
page that all use the same copy function
with the help of a data-key attribute:
Copy
The quick brown fox
Copy
The lazy dog
;
How It Works
-
The
data-sattributes on the buttons sets them up to send a signal namedcopyWithKey. -
When the signal comes in, bitty loops through all the elements with a
data-rattribute whose value matches thecopyWithKeysignal name.Each element is passed to the
copyWithKeyfunction as theelargument. Thesenderargument is populated by the button that sent the signal. -
Since there are multiple elements with the
data-r="copyWithKey"attribute we need a way to filter them down to just the one we want. The approach used here does the filtering by comparing thedata-keyvalues of the sending and receiving elements via the.prop()method that bitty adds to the incoming elements.When they match, the function calls the
.quickCopy()method with the elements to run the process.
Outro
Most of bitty is about setting up functions to
add your own features. The .quickCopy()
method is an exception. It's fully baked.
I found myself adding the functionality
so often it made since to include
it directly. Check it out if your
site has content you want to make it
easier for your visitors to grab.
-a
References
-
Bitty is a signals based framework rolled into a web component. You can find out more about it at bittyjs.com.
Endnotes
-
This example is using
bitty-9. At the time of this writing, that version is a private beta. The current production version of bitty isbitty-8. It provides the same functionality.