Search code examples
jqueryflashcopy-pastezeroclipboard

Format text for multiple elements using ZeroClipboard?


I'm trying to use ZeroClipboard to copy and format two elements for line breaks on a page using the following:

<script type="text/javascript">
        $(document).ready(function() {
            var clip = new ZeroClipboard($('#d_clip_button1, #d_clip_button2'), {
            moviePath: "/img/ZeroClipboard.swf"
            } );

        clip.on("dataRequested", function (client, args) {

        var txt = $('#copy_1, #copy_2').html();

        var windowsText = txt.replace(/\n/g, '\r\n');

        windowsText = windowsText.replace(/<br\s*\/?>/g, "\r\n");

        client.setText(windowsText);

        });

        clip.on( "load", function(client) {

        client.on( "complete", function(client, args) {
        // `this` is the element that was clicked

        alert("Copied to clipboard: " );
    });
  });
});                     
</script>

The text in my <pre id="copy_1">blah blah blah</pre> gets formatted ok.

However, my other element <pre id="copy_2">blah blah blah no. 2</pre> outputs the text from id="copy_1"

How do i get both elements to format correctly?


Solution

  • James Greene (https://github.com/JamesMGreene) came up with the answer:

    Your line:

    var txt = $('#copy_1, #copy_2').html();
    

    Will always only return the innerHTML of the element with the ID "copy_1" as jQuery's html() method is only performed on the first returned element in the set:

    In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned.

    Assuming your #d_clip_button[1/2] glued elements correspond to the #copy_[1/2] elements, you could do something like the following:

    clip.on("dataRequested", function(client, args) {
      var txt, windowsText,
          targetId = this.getAttribute("data-clipboard-target"),
          targetEl = !targetId ? null : document.getElementById(targetId);
      if (targetEl) {
        txt = $(targetEl).html();
        windowsText = txt.replace(/\n/g, "\r\n");
        windowsText = windowsText.replace(/<br\s*\/?>/g, "\r\n");
        client.setText(windowsText);
      }
    });