Properly resizing Disqus thread in an iframe

I had a use case where I needed to insert Disqus-threads into an iframe. Which should’ve been pretty easy.

The problem, however, is that the height of the Disqus-thread is dynamic which means that you cannot set the height beforehand. You need to set the height of the iframe when everything in the Disqus-thread is loaded. After a lot of searching I figured out the following solution for the problem.

Disqus pushes the events called “onReady” and “onNewComment” and you can use these events in the following way to get the height:

    <script type="text/javascript">
        var disqus_shortname = 'SHORTNAME'; // required: replace example with your forum shortname

        /* * * DON'T EDIT BELOW THIS LINE * * */
        (function () {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);

        function disqus_config() {
            this.callbacks.onReady = [function () {
                var newsId = getParameterByName('newsId');
                setTimeout(function() {
                    var frameHeight = $(document).height();
                    $('#disqus_iframe_' + newsId, top.document).attr("height", frameHeight);
                }, 2000);
            this.callbacks.onNewComment = [function () {
                var newsId = getParameterByName('newsId');
                var frameHeight = $(document).height();
                $('#disqus_iframe_' + newsId, top.document).attr("height", frameHeight);

        function getParameterByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(;
            return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

In the code above I execute code onReady and onNewComment. I grab the height of the document and then set the iframe height accordingly. Please notice, that it is not enough to just listen to the onReady-event as the complete list of comments is not loaded when this event is fired. Instead, you will have to set up a timer function and wait a couple of seconds in order to let all comments load properly – and then you can get the proper height. Not an elegant solution, but it works.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s