1

I have an Razor Pages application where I would like the user to be able to tweet from. I have gone through the documentation here and generated the code for a new button from here.

<a href="https://twitter.com/share?ref_src=twsrc%5Etfw" class="twitter-share-button" data-show-count="false">Tweet</a>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

If I put the code produced anywhere in the main part of my application it seems to work fine.

enter image description here

However, if I then try to put the tweet button inside a modal popup body it doesn't render.

enter image description here enter image description here

If I then just remove the <script> part of the generated code:

enter image description here enter image description here

The Anchor appears as a normal anchor without any of the additional functionality you get with the widget.js within the <script>.

Has anyone come across this or a similar issue before, or have any ideas to what could be causing the problem? I have been looking into it for a few days now and not getting very far.

CJH
  • 1,266
  • 2
  • 27
  • 61
  • See the many [questions on dynamic content in Bootstrap modals](https://stackoverflow.com/search?q=dynamic+content+in+bootstrap+modal). You need to initialize your script _after_ the modal is shown. – isherwood Oct 26 '21 at 12:48

1 Answers1

1

Try loading the script when the modal opens. You'll probably have a lay-out shift when the link is replaced by the button.

document
  .getElementById("myModal")
  .addEventListener("show.bs.modal", async function () {
    !(function (d, s, id) {
      var js,
        fjs = d.getElementsByTagName(s)[0];
      if (!d.getElementById(id)) {
        js = d.createElement(s);
        js.id = id;
        js.src = "https://platform.twitter.com/widgets.js";
        fjs.parentNode.insertBefore(js, fjs);
      }
    })(document, "script", "twitter-wjs");
  });

Script is slightly adapted from this answer.

Barabazs
  • 26
  • 4
  • Many thanks... I have since moved the project into a React application but will still give this a test out and may even be handy when I come to this again within the new App. Man thanks! – CJH Oct 27 '21 at 08:41