2

I need to add in some javascript code onto my page after an onclick. I have the following code but nothing happens on the button click and the page just outputs:

'); }); }); [button]

Here is my code:

<button type="submit" id="btn">button</button>

<div id="code"></div>

<script>
jQuery(document).ready(function () {
    jQuery('#btn').click(function(){
        jQuery('#code').append('<script>alert("WORKING");</script>');
    });
});
</script>
odd_duck
  • 3,941
  • 7
  • 43
  • 85
  • Your code seems to work in a jsbin: http://jsbin.com/likubo/1/edit – Sean O Feb 10 '15 at 18:18
  • why not just use a boolean variable to toggle the behavior on after the button is clicked? – pennstatephil Feb 10 '15 at 18:19
  • 2
    Why append a script that runs alert when you can just run the alert? – j08691 Feb 10 '15 at 18:19
  • alert was just an example, i'm actually wanting to put javascript tracking code in but this was much cleaner as an example – odd_duck Feb 10 '15 at 18:22
  • That's means you need to escape in some way the closing script tag, e.g using `jQuery('#code').append(' – A. Wolff Feb 10 '15 at 18:22
  • `.append(' – j08691 Feb 10 '15 at 18:23
  • Does appending a script even do anything? If it's not there on page load it won't do anything. – Waxi Feb 10 '15 at 18:24
  • would you be able to wrap that tracking code in a function and then call that function with whatever trigger you want? (so that it'll only track/do whatever when the function its wrapped in is called) – indubitablee Feb 10 '15 at 18:42

2 Answers2

0

I got it to work by escaping the forward slash in </script>. The closing script tag is not allowed in inline Javascript, as it messes with the way the code is parsed:

        jQuery('#code').append('<script>alert("WORKING");<\/script>');
0

This is actually a surprisingly simple task and doesnt require Jquery -- although you can execute the function with or without Jquery, however you like.

function AddNewExternalScriptToThisPage(ExternalScriptURLPath) {
    var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = ExternalScriptURLPath;
    headID.appendChild(newScript);
}

You can also add in an onload event if you want:

function AddNewExternalScriptToThisPage(ExternalScriptURLPath) {
    var headID = document.getElementsByTagName("head")[0];
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = ExternalScriptURLPath;
    newScript.onload=scriptHasLoadedContinue;
    headID.appendChild(newScript);
}
Bangkokian
  • 6,548
  • 3
  • 19
  • 26