Search code examples
javascripthtmlcsspluginssweetalert2

Loading scripts after SweetAlert2 modal has loaded


I'm using the ShareThis share button generator, which renders social media share buttons by looking for a class sharethis-inline-share-buttons. The problem is that I need to render the share buttons inside of a SweetAlert2 modal, which are dynamically generated and don't exist as markup on the page like most modal solutions. This means that any sharethis-inline-share-buttons class I try to place inside a SweetAlert2 modal doesn't exist at the time that the ShareThis plugin looks for it.

While it provides a decent plugin the logged-in experience on the ShareThis site is terrible, and SweetAlert 2 doesn't seem to offer anything in its API to hook a script into before the modal has been generated.

Here is the code I'm currently using to trigger SweetAlert2:

shareText = `Share this website:
<br>
<div class="share-container">
<div class="sharethis-inline-share-buttons"></div>
</div>`;

modal.fire({
    titleText: "Spread the word",
    html: shareText,
    icon: "info",
    backdrop: `rgba(0,0,0,0.7)`
});

Is what I want possible?


Solution

  • I decided to contact ShareThis support to see if it was possible to load their Share Buttons only once SweetAlert 2 had been loaded. I had figured out a mostly working solution before receiving their reply, but I could have just waited a day or so for them to respond because they not only fixed the problem with a single line of code, they also took the time to look into SweetAlert 2's documentation to determine how it should be implemented (shoutout to Enrique over at the ShareThis team).

    The solution is to use SweetAlert 2's didOpen or didRender functions, which allow for the execution of a function after the modal has been synchronously or asynchronously rendered, respectively. From there it's a simple matter of manually initialising the Share Buttons.

    modal.fire({
        titleText: "Spread the word",
        html: shareText,
        icon: "info",
        backdrop: `rgba(0,0,0,0.7)`,
        didOpen: function () {
            window.__sharethis__.initialize();
        }
    });