I am trying to write a basic blogging platform, and I want to offer users the ability to copy code within a pre block to their clipboard.
I am using ZeroClipboard to achieve this. Once the document is ready, I loop through each pre
on the page, adding a clipboard item to it as follows:
$(document).ready(function() {
ZeroClipboard.setMoviePath( 'ZeroClipboard/ZeroClipboard.swf' );
var preNum = 1
$('pre').each(function() {
// Get a unique id for the element I will be inserting
var id = 'copy-btn-' + preNum++
// Capture the text to be copied to the clipboard
var text = $(this).text()
// Insert the element, just before this
$('<div class="copy-btn" id="' + id + '-cont"><i class="icon-file icon-white" id="' + id + '"></i></div>').insertBefore(this)
// Capture the newly inserted element
var elem = $(this).prev()
// Create the clip, and glue it to the element
var clip = new ZeroClipboard.Client();
clip.setText(text)
clip.glue(elem)
})
});
When I try to do this, the javascript console reports: Uncaught TypeError: Cannot read property 'zIndex' of undefined
My current understanding of the problem is that the inserted element is not yet available in the dom when I try to glue the clip to it, which is why no gluing is occurring.
Anybody know how I might be able to accomplish this?
From the Gluing instructions:
You can pass in a DOM element ID (as shown above), or a reference to the actual DOM element object itself.
Your code doesn't work because you're passing a jQuery object to it.
You can pass the ID:
clip.glue(id + '-cont')
Or an actual DOM element reference:
clip.glue(elem[0])
The above example uses the shorthand for the .get()
jQuery object method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With