Search code examples
javascriptajaxinnerhtmlzeroclipboard

innerHTML to insert script in body (for ZeroClipboard) not working


I'm building <div> elements using AJAX, and I want to add ZeroClipboard functionality. Firebug shows the code is building correctly, and when I copy it into a raw HTML test page it works too. The builds are not happening at onload, but down the track.

The code is as follows, calling some functions that create the new elements:

dom_append_child_with_onclick ("img",export_id,"icon_active",report_heading_id, "event.cancelBubble = true;");
dom_append_child ("div",export_script_id,"",report_heading_id);
text = "<script language='JavaScript'>var clip" +rnum +"=new ZeroClipboard.Client();clip"+rnum+".setText('');clip"+rnum+".addEventListener('mouseDown',function(client){alert('firing');clip"+rnum+".setText(document.getElementById('SL40').value);});clip"+rnum+".glue('XR"+rnum+"','RH"+rnum+"');</script>";
document.getElementById(export_script_id).innerHTML=text;

My question: when you insert a script into the <body>, do you have to do something to get it to fire? The script appears not to be doing its thing, and I can't get the alert 'firing' to display.

Note: the cancelBubble is to stop the onClick function of the underlying element. It may be unnecessary if I can get the flash working.

Thanks.


Solution

  • You can just inject your script into the page as a DOM object, but this does not work in all browsers:

    var s = document.createElement("script");
    s.type = "text/javascript";
    s.innerText = "var clip" +rnum +"=new ZeroClipboard.Client();clip"+rnum+".setText('');clip"+rnum+".addEventListener('mouseDown',function(client){alert('firing');clip"+rnum+".setText(document.getElementById('SL40').value);});clip"+rnum+".glue('XR"+rnum+"','RH"+rnum+"');";
    document.getElementsByTagName("head")[0].appendChild(s);
    

    Or, for better compatibility, you probably want to just declare a function which sets this up in your page, and then just call the function with the rnum as the parameter.

    e.g.

    function useZeroClipboard(rnum) {
        window["clip" + rnum] = new ZeroClipboard.Client();
        cwindow["clip" + rnum].setText('');
        window["clip" + rnum].addEventListener('mouseDown', function(client){
            alert('firing');
            window["clip" + rnum].setText(document.getElementById('SL40').value);
        });
        window["clip" + rnum].glue('XR"+rnum+"','RH"+rnum+"');
    }
    

    Then you can just call that in your code:

    useZeroClipboard(rnum);
    

    Instead of writing the script block.