#StackBounty: #javascript #jquery #toggle jQuery .toggle() button needs to be clicked twice

Bounty: 50

I’m trying to do two things:

  1. load the Disqus script embed.js after the "Show comments" button is clicked.
  2. Hide the disqus_thread div via the same button while changing the text in the button.

The problem is that after page load, I have to click "Show Comments" twice; the first click loads the embed.js and that should toggle disqus_thread to visible, but I have to click a second time to see the disqus_thread. (It doesn’t matter than embed.js is loaded; I only want to toggle the div and hide it.)

Note: the {{ }} constructs in showComments() are , but I don’t think they are the issue.

    <button id="disqus-button" onclick="showComments()">Show comments</button>
    
    <script>
    
    $( document ).ready(function() {
    $('#disqus-button').click(function(){
        $('#disqus_thread').toggle();
        $(this).text( $(this).text() == 'Show Comments' ? "Hide Comments" : "Show Comments");
    });
    });
    
    </script>
    
    <div id="disqus_thread"></div>
    
    <script>
    
    function showComments() {
        var disqus_config = function () {
        {{with .Params.disqus_identifier }}this.page.identifier = '{{ . }}';{{end}}
        {{with .Params.disqus_title }}this.page.title = '{{ . }}';{{end}}
        {{with .Params.disqus_url }}this.page.url = '{{ . | html  }}';{{end}}
        };
        var d = document, s = d.createElement('script'); s.async = true;
        s.src = '//' + "{{ .Site.DisqusShortname }}" + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    }

</script>


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.