/ Gists / Iframe - autoheight
On gists

Iframe - autoheight

JavaScript

iframe-autoheight.js Raw #

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    

</head>
<body>
    
    <h1>test iframu</h1>
    <iframe onload="resizeIframe(this)" src="http://localhost/xxx/b.php" frameborder="1"></iframe>


    <script type="text/javascript">
        function resizeIframe(iframe) {
          iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
        }
    </script>
</body>
</html>

help.js Raw #

// https://stackoverflow.com/questions/12267010/how-can-i-detect-whether-an-iframe-is-loaded/12267180

// vanilla
window.onload=function(){
    var ifr=document.getElementById('MainPopupIframe');
    ifr.onload=function(){
        this.style.display='block';
        console.log('laod the iframe')
    };
    var btn=document.getElementById('click');    
    btn.onclick=function(){
        ifr.src='https://heera.it';    
    };
};


// jquery
$(function(){
    $('#click').on('click', function(){
        var ifr=$('<iframe/>', {
            id:'MainPopupIframe',
            src:'https://heera.it',
            style:'display:none;width:320px;height:400px',
            load:function(){
                $(this).show();
                alert('iframe loaded !');
            }
        });
        $('body').append(ifr);    
    });
});

// or 
$(function(){
    $('#MainPopupIframe').load(function(){
        $(this).show();
        console.log('iframe loaded successfully')
    });
        
    $('#click').on('click', function(){
        $('#MainPopupIframe').attr('src', 'https://heera.it');    
    });
});