Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I glue() a ZeroClipboard clip to a newly inserted element?

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?

like image 202
finiteloop Avatar asked Nov 04 '22 13:11

finiteloop


1 Answers

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.

like image 199
Fabrício Matté Avatar answered Nov 09 '22 08:11

Fabrício Matté