Tutorial: Copy BBCode / HTML Content to clipboard and preserve formatting

1 favourites
  • 1 posts
From the Asset Store
A complete set of graphical user interface (GUI) to build 2D video games. Suitable for casual games
  • Hey everyone!

    I was making a web app that generates and formats text and stumbled upon the following issue:

    I could not make a button that lets the user copy the text and keep the formatting.

    When you use the built-in clipboard plugin and copy the text of a text field (using Object.Text), the formatting through BBCode is being copied as plain text. For example, This would not look cursive but rather just show the BBCode brackets with the i's inside of them.

    So I tried doing it with an html field, I set the HTML's content to the text field's BBCode-formatted text and it displays it nicely, however, when I copy the HTML.HTMLContent, the text doesn't copy with the right format and <em> elements are being shown instead of the text being cursive etc.

    In the end, I managed to find a solution to this problem which I wanted to share with you and it does not require any plugin, just a few lines of javascript code which you can simply include in the construct editor thanks to the built-in scripting feature.

    What you need to do beforehand, is to set the text of an html element to the formatted text that you want to copy and set the ID of the html element (in the construct inspector) to "result" (you can pick a different id, but you have to change it in the js code accordingly).

    So in the event sheet, I put the following script under my button press event:

    function copyToClip(str) {
     function listener(e) {
     e.clipboardData.setData("text/html", str);
     e.preventDefault();
     }
     document.addEventListener("copy", listener);
     document.execCommand("copy");
     document.removeEventListener("copy", listener);
    };
    copyToClip(document.getElementById('result').innerHTML);
  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)