Search code examples
jquerytwitter-bootstrappopover

External HTML file in Bootstrap Popover content


When I use iframe to load external html file in popover content, it is restricting to popup height. But I want popup height to be auto. Some one help me out .!

$(document).ready(function(){
  $('.pop-right').popover({ 
title : 'Loading External File',
html : true,
placement : "right",
content: function () {
      return '<iframe src="popover-content.html" style="border:none"></iframe>';    
        });
    }
  });
});

Solution

  • When you are not cross-domaining', i.e. you are not loading google.com or similar into the iframe, it is relatively easy.

    Declare the below function, which takes the popover element (.pop-right) and the popover content <iframe> as parameters :

    function adjustPopover(popover, iframe) {
        var height = iframe.contentWindow.document.body.scrollHeight + 'px',
            popoverContent = $(popover).next('.popover-content');
        iframe.style.height = height;
        popoverContent.css('height', height);
    }
    

    1) get scrollHeight of the iframe (the real height)
    2) get the .popover-content <div> associated with .pop-right
    3) set .popover-content to the real height, and do the same with the <iframe> to avoid scrollbars.

    Then, in your popover initialisation call adjustPopover() in the iframes onload-event with onload="adjustPopover(&quot;.pop-right&quot;, this);" :

    $('.pop-right').popover({ 
       title : 'Loading External File',
       html : true,
       placement : "right",
       content: function() {
           return '<iframe src="content.html" style="border:none" onload="adjustPopover(&quot;.pop-right&quot;, this);"></iframe>';    
       }
    });
    

    It is a good idea to set a minimum height for the iframes. If you dont do that, popovers will always have at least the browsers default height of an iframe, in chrome 150px.

    iframe {
        height: 40px;
        min-height : 40px;
    }
    

    Here is an jsfiddle example loading the jsfiddle file /css/normalize.css -> http://jsfiddle.net/ovky3796/

    As you see, I also changes .popover max-width in the demo. This is for demonstration only, if you want to adjust the width of the popover according to the content of the <iframe>, do the same as above with scrollWidth instead.