Monday 28 September 2020

jQuery .toggle() button needs to be clicked twice

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 () {
        this.page.identifier = '';
        this.page.title = '';
        this.page.url = '';
        };
        var d = document, s = d.createElement('script'); s.async = true;
        s.src = '//' + "" + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    }

</script>


from jQuery .toggle() button needs to be clicked twice

No comments:

Post a Comment