Javascript function not working when placed in Text Block

The main reason it’s not working is that the onclick() attribute is not an allowed attribute in the editor. Probably for security reasons.

The alternative is to add the click event in the script. So instead of the onclick="myFunction()", add an ID, myButton to the button, then these lines:

var myButton = document.getElementById( 'myButton' ); 
myButton.addEventListener( 'click', myFunction );

However I had trouble with this because the editor was adding divs and styling in between the script for some reason. A safer way to do this would be a custom Shortcode.

This code, added in functions.php or in a custom plugin, will create a shortcode that you can use to output your HTML and JS like this:

[copy_text]

The code is:

function wpse_298687_shortcode() {
    // Start capturing output to return at the end.
    ob_start();
    ?>

    <input id="myInput" style="width: 600px;" readonly="readonly" type="text" value="Important Data">
    <button onclick="myFunction()">Copy</button>

    <script>
        function myFunction() {
            var copyText = document.getElementById('myInput');
            copyText.select();
            document.execCommand('copy')
            alert('Data copied to clipboard');
        }
    </script>

    <?php
    // Return captured output.
    return ob_get_clean();
}
add_shortcode( 'copy_text', 'wpse_298687_shortcode' );

I’ve tested it and it works. However there are many ways it could be improved which I haven’t gone into too much detail on to avoid making it too confusing.

For example, if you use this shortcode multiple times it won’t work properly because the input and button and IDs, and IDs shouldn’t be duplicated. Ideally the code would use more generic classes.

The other problem with using it multiple times is that you’ll be defining the myFunction() function more than once which will throw errors. Ideally the script would exist in a separate file enqueued by the shortcode so that all uses of the shortcode share a single script. This means the script should be written to allow any given button to copy the text from any given box. Maybe via a data attribute or shared parent.

That’s all getting quite complex, so for now just focus on the ability to use shortcodes to create text snippets that can be used to call in code from somewhere else so that it doesn’t get interfered with by the editor.