Zeroclipboard javascript copy button within a Bootstrap Modal – Mr. Joel Kemp

If you need “copy to clipboard” functionality for your website, then you’ll likely need a library that uses flash to facilitate this feature. For a share panel that I built out for YouNow, I used the ZeroClipboard library. Here’s how to get it to work properly with Twitter Bootstrap modals.

Zeroclipboard works well if you bind it to a button that has absolute/relative positioning. If you have a copy button in a bootstrap modal, then the button has a fixed position. This becomes problematic if the modal launches while the user has the background page scrolled. The flash object that sits on top of the bound copy button won’t move with the modal, so the flash object will stay at the original/unscrolled position of the button.

A quick fix is to change the styling of the main zero-clipboard element (“#global-zeroclipboard-html-bridge”) to have a fixed position. This isn’t great since you’d imagine the library initialization being configurable for this (which it doesn’t); however, this gets the job done with minimal effort. The official fix for binding to fixed-position elements seems to be coming in the 1.2 milestone of the library, but good luck waiting on that.

Here’s the code:

document.getElementById('global-zeroclipboard-html-bridge').style.position = 'fixed'

With this fix, the copy button should work even with scrolling.